【发布时间】:2016-12-05 21:15:14
【问题描述】:
我正在使用 socket io 来构建一个聊天应用程序。
当“用户 x”从聊天中断开时,我想打印到控制台日志:“再见用户 x”。
为此,我需要将用户名作为参数传递给断开连接事件。
问题是我不知道如何将数据传递给断开事件:
socket.on('disconnect', function(){...})
当用户断开连接时自动调用它。
我需要类似的东西
socket.on('disconnect', function(user_name){
console.log('bye '+user_name);
})
但如果可能的话(是吗?)那么我怎样才能在客户端传递这个参数(我的情况,角度)?
我完整的 socket io server.js 代码如下。
io.on('connection', function(socket){
io.emit('chat_message', "welcome");
socket.on('room', function(room) {
socket.join(room);
});
socket.on('chat_message', function(data){
socket.broadcast.to(data.room).emit('chat_message',data.msg);
});
socket.on('info_message', function(data){
socket.broadcast.to(data.room).emit('info_message',data.msg);
});
socket.on('disconnect', function(){
console.log('bye '+socket.id);
io.emit('chat message', "Bye");
});
});
【问题讨论】:
-
我假设您将需要一个辅助函数,该函数最初将房间、用户和套接字 ID 存储在连接时的对象/数组中。断开连接时,您将能够将 socket.id 与对象/数组中的用户名匹配并根据需要显示。
-
谢谢,socket id 对于每个用户是唯一的还是每个房间唯一的?
-
好像:socket.io/docs/rooms-and-namespaces -
Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id. -
我不认为你可以:当
disconnect触发时,已经为时已晚......
标签: javascript angularjs node.js socket.io