最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论