基本上我正在尝试使用Node.JS和angular创建一个快速聊天室。
我已经使用过其他套接字事件但是他们工作了我不太明白为什么他们现在不想工作。真正奇怪的是登录工作正常并且相当不错,但是当它涉及注销,甚至使用我的disconnect方法时,服务器端没有任何事情发生,使用disconnect函数,console.log
工作正常。但它不会排放。
在角度方面,我的所有console.log
都在运行,但在注销或discconecnting时没有任何事件触及服务器。
节点内部我有三个事件
socket.on('chat:userLogin', function(user) {
socket.join('online-users');
chatRoom[user.id] = user
console.log('User Has logged in, chat room contains: ', chatRoom);
io.sockets.in('online-users').emit('chat:usersOnline', chatRoom)
})
socket.on('chat:userLogout', function(userId) {
console.log('User Id ' + userId + 'is logging out');
delete chatRoom[userId]
console.log('User Has logged out, chat room contains: ', chatRoom);
io.sockets.in('online-users').emit('chat:userLeave', chatRoom);
socket.leave('online-users');
})
socket.on('disconnect', function() {
var userRoom = rooms[socket.roomId]
if (chatRoom[socket.userId])
delete chatRoom[socket.userId]
io.sockets.in('online-users').emit('chat:userLeave', socket.userId);
console.log('Emitting that users have left to: ', io.sockets.in('online-users'));
socket.leave('online-users');
}
在角度上我有两个发出这两个事件的函数
this.logout = function(userId) {
console.log('Logging user out: ', userId);
Socket.emit('chat:userLogout', userId);
console.log('Logged out user?');
delete this.userStore[userId]
}
this.login = function(userId) {
console.log('Getting online user ', userId);
var self = this;
User.get({id: userId}, function(user) {
self.userStore[userId] = user;
Socket.emit('chat:userLogin', user);
});
}
答案 0 :(得分:0)
它可能会解决您的问题,但您应该使用socket.broadcast.to('roomname'),除非您要将消息发送到房间中的所有套接字(包括发送消息的套接字)。所以你的代码看起来像
socket.on('chat:userLogin', function(user) {
socket.join('online-users');
chatRoom[user.id] = user
console.log('User Has logged in, chat room contains: ', chatRoom);
// emit to everyone else except the sender
socket.broadcast.to('online-users').emit('chat:usersOnline', chatRoom);
})
socket.on('chat:userLogout', function(userId) {
console.log('User Id ' + userId + 'is logging out');
delete chatRoom[userId]
socket.leave('online-users');
// leaving the chat room here means we can emit to all people in the room
io.sockets.in('online-users').emit('chat:userLeave', chatRoom);
console.log('User Has logged out, chat room contains: ', chatRoom);
})
socket.on('disconnect', function() {
var userRoom = rooms[socket.roomId]
if (chatRoom[socket.userId])
delete chatRoom[socket.userId]
socket.leave('online-users');
io.sockets.in('online-users').emit('chat:userLeave', socket.userId);
console.log('Emitting that users have left to: ', io.sockets.in('online-users'));
}
查看this question了解详情。