javascript - How to identify users in socket.io? - Stack Overflow

I'm using socket.io to build a chat application. But I don't know how to identify which user

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

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);
    });
Share Improve this question asked Jan 20, 2015 at 17:34 ShonaliShonali 672 silver badges5 bronze badges 2
  • did you try to send userID with the message? – hrust Commented Jan 20, 2015 at 17:40
  • Possible duplicate of Socket.io Identify User for Socket – Raul Rene Commented Apr 30, 2018 at 12:32
Add a ment  | 

1 Answer 1

Reset to default 4

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745142287a4613484.html

相关推荐

  • javascript - How to identify users in socket.io? - Stack Overflow

    I'm using socket.io to build a chat application. But I don't know how to identify which user

    3小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信