我正在尝试使用socket.io创建一个房间以便在我的网站上聊天。
不幸的是,即使消息发送正确并且两个用户都加入了同一个房间,也不会收到消息。
到目前为止,这是我的代码:
chat.component.ts
:
// both users joining the same room with their matchId
// __________________________________________________________________
joinRoom(matchId) {
try {
this.socket = io.connect('http://localhost:3000');
this.socket.emit('join room', matchId.toString());
} catch (e) {
console.log('Could not connect socket.io');
}
}
// emiting the message object
// __________________________________________________________________
this.socket.emit('send message', obj);
// receiving the message object and pushing it to the messageList
// __________________________________________________________________
receive = (obj) => {
if (obj) {
this.messageList.push(obj);
}
}
ngOnInit() {
try {
this.socket.on('receive message', this.receive);
} catch (e) {
console.log('Could not connect socket.io');
}
}
backend
:
io.sockets.on('connection', function(socket) {
var roomId;
socket.on('join room', function(room) {
socket.join(room);
console.log('a user connected to room', room);
roomId = room;
});
socket.on('send message', (obj) => {
socket.broadcast.to(roomId).emit('receive message', obj);
});
});
我同时收到join room
和send message
事件。
我该怎么办才能在房间里接收消息?
谢谢!