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?
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With