【问题标题】:How to identify users in socket.io?如何在 socket.io 中识别用户?
【发布时间】:2015-01-21 01:47:44
【问题描述】:

我正在使用 socket.io 构建一个聊天应用程序。但我不知道如何识别是哪个用户发送了这条消息。 Express 中没有“req”(请求)变量。那么在这种情况下,我该如何安全地识别发件人呢?

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

【问题讨论】:

标签: javascript node.js socket.io


【解决方案1】:

每个 Socket 都有一个唯一的 ID,可以让您识别连接。

所以在这种情况下它会是

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

Socket.io API 文档应该会有所帮助 http://socket.io/docs/server-api/#socket

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 2021-12-14
    • 2016-07-09
    • 2020-04-13
    • 1970-01-01
    相关资源
    最近更新 更多