I am using socket_io_client package in a flutter app for chatting, when I emit an event from my side to the server side it works well, however I don't receive an event from the server side
Here is the server side code using Node JS and it uses Socket package ^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');
}
});
and here is my flutter code I use socket_io_client of version ^2.0.0-beta.4-nullsafety.0 , I can send the 'sendmesssage' event to the server, but I don't receive 'receivemessage' event
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();
}
}
I can't find the problem at all