我正在尝试实现一个多用户通信应用程序。我想用他的 id 来识别用户的套接字,所以我可以将套接字的 id 设置为用户的 id
socket.id=user.userId;
这可能会帮助你
io.sockets.on('connection', function (socket) {
console.log("==== socket ===");
console.log(socket.id);
socket.broadcast.emit('updatedid', socket.id);
});
您可以在客户端保存套接字 ID。当您想要 1-1 消息(私人聊天)时,请使用更新的套接字 id。像这样的东西:
io.sockets.socket(id).emit('private message', msg, mysocket.id)
您可以这样做,但使用不与 Node.js 或任何其他框架键冲突的属性
socket.myappsuperuserid = user.userId;
这里
客户端
var socket = io.connect();
socket.on('connect', function () {
console.log("client connection done.....");
socket.emit('setUserId','random value');
});
在服务器端
io.sockets.on('connection', function (socket) {
socket.on('setUserId',function(uId){
socket.userId = uId;
});
});
这可能会有所帮助...
在 socket.io 中,当用户连接时,socket.io 会生成一个唯一的 socket.id,它基本上是一个随机唯一的不可猜测的 id。我要做的是在我连接后调用socket.join('userId')。基本上在这里,我用我的 userId 为这个套接字分配了一个房间。然后每当我想向这个用户发送一些东西时,我都会喜欢这个 io.to(userId).emit('my message', 'hey there?')。希望这有帮助。