简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM