Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify users in socket.io?

I'm using socket.io to build a chat application. But I don't know how to identify which user sent this message. There is no "req" (request) variable, as there is in Express. So how would I safely identify the sender in this case?

socket.on('chatroom message ', function(msg){
        console.log("sending msg: "+msg);
        io.emit('chatroom message ', msg);
    });
like image 357
Shonali Avatar asked Oct 21 '25 06:10

Shonali


1 Answers

Each Socket has a unique ID which allows you to identify the connection.

So in this case it would be

socket.on('chatroom message ', function(msg){
        console.log("sending msg from " + socket.id + ": "+msg);
        io.emit('chatroom message ', msg);
    });

The Socket.io API documentation should help http://socket.io/docs/server-api/#socket

like image 121
Glenn Flanagan Avatar answered Oct 23 '25 21:10

Glenn Flanagan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!