开发者

Get the client id of the message sender in socket.io?

开发者 https://www.devze.com 2023-04-06 15:10 出处:网络
on the server开发者_如何学Python side i got socket.on(\'chat\', function (data) { io.sockets.socket(data.clientid).emit(\'chat\', {

on the server开发者_如何学Python side i got

socket.on('chat', function (data) {
    io.sockets.socket(data.clientid).emit('chat', {
        msg: data.msg,
        senderid : senderid
    });
});

How can I get the get the senderid without the sender having to post their clientid through with the message?


It turns out I can just use socket.id of the user sending through a msg to get their clientid, such as:

  socket.on('chat', function (data) {
      io.sockets.socket(data.clientid).emit('chat', {
          msg: data.msg,
          senderid : socket.id
      }); 
  });

Originally I thought I could just fetch the clientid by doing :

  io.sockets.on('connection', function (socket) {
     clientid = socket.id;

But clientid will be the last person who connected in this instance, not the last person who sent through a chat


I'd suggest sending over a username (make sure it's unique) and keeping an object of client ids associated with usernames in memory.

0

精彩评论

暂无评论...
验证码 换一张
取 消