Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

on the server 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?

like image 964
uguMark Avatar asked Sep 22 '11 18:09

uguMark


People also ask

How do I check if a message sent through Socket.IO is read?

You will have to send a message back when the message is read. There is no notion of when something is "read" in socket.io. That's something you would have to invent in your own user interface and when you consider it read, you could send a message back to the sender that indicates it is now read.

How do I send a message to socket ID?

To send a message to the particular client, we are must provide socket.id of that client to the server and at the server side socket.io takes care of delivering that message by using, socket.broadcast.to('ID'). emit( 'send msg', {somedata : somedata_server} ); For example,user3 want to send a message to user1.

What is the difference between Socket.IO and socket IO client?

socket-io. client is the code for the client-side implementation of socket.io. That code may be used either by a browser client or by a server process that is initiating a socket.io connection to some other server (thus playing the client-side role in a socket.io connection).


2 Answers

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

like image 137
uguMark Avatar answered Oct 01 '22 04:10

uguMark


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

like image 28
Mike Avatar answered Oct 01 '22 03:10

Mike