我正在node.js(express)和前端之间初始化socket.io。基本上,从nodejs,我正在向私有频道广播。然后,我也想在同一频道上收到此广播的回叫。
这是server.js中的设置:
const port = process.env.PORT || 3000;
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const api = require('../api/AuthController')
var server = http.listen(3000, () => {
console.log('server is running on port', server.address().port);
});
const routes = require('../api/routes');
routes(app,io);
//socket config
global.io = io; //added
然后在AuthController中,我正在使用global.io进行发射,并在私有通道中进行接收:
global.io.emit(`news${user._id}`, { hello: 'new request');
global.io.on('conection', function (socket) {
socket.on(`news${user._id}`, function (message) {
console.log('from console', message.value);
});
});
我可以很好地向前端发射信号,但是当前端在同一通道上发射回来时,我什么也收不到。
感谢您的帮助。
谢谢
修改
前端代码:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:adhara_socket_io/adhara_socket_io.dart';
import 'package:geocoder/geocoder.dart';
const String URI = "http://10.0.2.2:3000/";
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
_MyHomePageState();
List<String> toPrint = ["trying to connect"];
SocketIOManager manager;
Map<String, SocketIO> sockets = {};
Map<String, bool> _isProbablyConnected = {};
bool newtripRequest = false;
var pickupController;
var dropoffController;
SocketIO socketController;
var driver = 'driver';
String socketIdentifier;
@override
void initState() {
super.initState();
manager = SocketIOManager();
initSocket("default");
}
@override
void dispose() {
super.dispose();
}
initSocket(String identifier) async {
setState(() => _isProbablyConnected[identifier] = true);
SocketIO socket = await manager.createInstance(SocketOptions(
//Socket IO server URI
URI,
nameSpace: (identifier == "namespaced") ? "/adhara" : "/",
//Query params - can be used for authentication
query: {
"auth": "--SOME AUTH STRING---",
"info": "new connection from adhara-socketio",
"timestamp": DateTime.now().toString()
},
//Enable or disable platform channel logging
enableLogging: false,
transports: [
Transports.WEB_SOCKET /*, Transports.POLLING*/
] //Enable required transport
));
setState(() {
socketIdentifier = identifier;
});
socket.onConnect((data) {
pprint("connected...");
pprint(data);
sendMessage('news', 'yes', socketIdentifier);
});
socket.onConnectError(pprint);
socket.onConnectTimeout(pprint);
socket.onError(pprint);
socket.onDisconnect(pprint);
socket.on("news", (data) => newTripRquest(data));
socket.connect();
sockets[identifier] = socket;
}
bool isProbablyConnected(String identifier) {
return _isProbablyConnected[identifier] ?? false;
}
disconnect(String identifier) async {
await manager.clearInstance(sockets[identifier]);
setState(() => _isProbablyConnected[identifier] = false);
}
sendMessage(privateChannel, messageBody, identifier) {
//pprint("sending message from '$identifier'...");
sockets[identifier].emit(driverChannel, [
{'response' : messageBody}]);
//pprint("Message emitted from '$identifier'...");
}
pprint(data) {
setState(() {
if (data is Map) {
data = json.encode(data);
}
print(data);
toPrint.add(data);
});
}
答案 0 :(得分:0)
您遇到了拼写错误(“对接”),并且emit对象中没有右括号。
这是AuthController代码的固定版本:
global.io.emit(`news${user._id}`, { hello: 'new request' });
global.io.on('connection', function (socket) {
socket.on(`news${user._id}`, function (message) {
console.log('from console', message.value);
});
});
希望对您有帮助!