【发布时间】:2022-01-25 01:06:16
【问题描述】:
我在颤振应用程序中使用socket_io_client package 进行聊天,当我从我的一侧向服务器端发出事件时,它运行良好,但是我没有从服务器端收到事件
这是使用 Node JS 的服务器端代码,它使用 Socket 包 ^4.4.0
const io = require('socket.io')(6600, {cors: {original: '+'}});
io.on('connection', (socket) => {
console.log('user connected');
socket.on('userid', (userId) => {
console.log(userId);
socket.userID = userId;
console.log(socket.userID);
socket.join(socket.userID);
// console.log(io.sockets.adapter.rooms[socket.userID].length);
});
// send all sockets of the same user to the same room
socket.on('sendmessage', ({content, senderId, receiverId}) => {
console.log(content);
console.log(senderId);
console.log(senderId === socket.userID);
console.log(receiverId);
socket.to(receiverId).to(senderId).emit('receivemessage', {
content,
senderId,
receiverId,
});
});
socket.on('disconnect', async () => {
const matchingSockets = await io.in(socket.userID).allSockets();
const isDisconnected = matchingSockets.size === 0;
if (isDisconnected) {
console.log('user disconnected');
}
});
这是我使用 ^2.0.0-beta.4-nullsafety.0 版本的 socket_io_client 的颤振代码,我可以将 'sendmesssage' 事件发送到服务器,但我没有收到 'receivemessage' 事件
class SocketIO extends ChangeNotifier {
///Socket object
IO.Socket socket;
///Connects to socket server using [userId]
void connectToServer(BuildContext context, String userId) {
socket = IO.io(
'http://10.0.2.2:6600',
IO.OptionBuilder()
.setTransports(['websocket']) // for Flutter or Dart VM
.disableAutoConnect() // disable auto-connection
.build());
socket = socket.connect();
print('connection id: ' + userId);
socket.onConnect((_) {
print('connect');
socket.emit('userid', userId);
socket.on( // not working
'receivemessage',
(data) => () {
print('message recieved');
Provider.of<Messaging>(context, listen: false).receiveMessage(
context,
data['content'],
data['senderId'],
data['receiverId']);
});
});
socket.onDisconnect((_) => {print('disconnect')});
}
void sendMessage(String senderId, String receiverId, String text) {
print(socket.connected);
socket.emit('sendmessage',
{'content': text, 'senderId': senderId, 'receiverId': receiverId});
print('sender id: $senderId');
}
void disconnect() {
socket.off('privateMessage');
socket.disconnect();
}
}
我根本找不到问题
【问题讨论】:
-
{cors: {original: '+'} - 可能是无效的 cors 配置
-
你知道什么是正确的 cors 配置吗?因为它对邮递员很好
-
{cors: {origin: '*'}} 应该允许所有请求,顺便说一句,邮递员完全忽略了 cors
-
我把它改成'*'还是不行
-
你是不是也把原件改成原件了?)
标签: node.js flutter sockets websocket socket.io