我可以将自己的id提供给nodejs中的连接套接字

时间:2012-05-17 11:11:54

标签: node.js

我正在尝试实施多用户通信应用。我想用他的id识别用户的套接字,所以我可以将套接字的id设置为用户的id,如

socket.id=user.userId;

4 个答案:

答案 0 :(得分:3)

这可能对您有所帮助

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) 

答案 1 :(得分:1)

这里

客户端

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;
        });
});

这可能会有所帮助......

答案 2 :(得分:0)

您可以执行此操作,但使用不与Node.js或任何其他框架键冲突的属性

socket.myappsuperuserid = user.userId;

答案 3 :(得分:0)

在socket.io中,当用户连接时,socket.io将生成一个唯一的socket.id,它基本上是一个随机唯一的unguessable id。我所做的就是在我连接后调用socket.join(' userId')。基本上我在这里用我的userId为这个套接字分配一个房间。然后每当我想向这个用户发送内容时,我都喜欢这个io.to(userId).emit('我的消息','嘿那里?') 。 希望这有帮助。