socket.io将userId分配给sessionId

时间:2011-08-13 03:46:51

标签: node.js socket.io

我试图将client.sessionId转换为我的变量Response.UserID的值,我得到的只是我的响应中的NaN。我尝试了几个像toString但仍然得到NaN或[全局对象]有没有其他人试图这样做?

以下是一些示例代码..

socket.on('connection', function(client){
    // Success!  Now listen to messages to be received
    client.on('message',function(event){
        var Response = JSON.parse(event);
        if(Response.UserID == null){
            client.broadcast(event);
            console.log('Received message from client!',event);
        }
        else{
            console.log('Received message from client!',event);
            client.broadcast(JSON.stringify({'UserName': '', 'Message': Response.UserID + ' is now connected'}));
        }
    });
    client.on('disconnect',function(){
        client.broadcast(JSON.stringify({ 'UserName': '', 'Message':client.sessionId + ' left the conversation'}));
    });

});

该代码工作正常,当用户断开连接时,它将显示sessionId。这是我想要的但是

socket.on('connection', function(client){
    // Success!  Now listen to messages to be received
    client.on('message',function(event){
        var Response = JSON.parse(event);
        if(Response.UserID == null){
            client.broadcast(event);
            console.log('Received message from client!',event);
        }
        else{
            console.log('Received message from client!',event);
                client.sessionId = Response.UserID;
            client.broadcast(JSON.stringify({'UserName': '', 'Message': Response.UserID + ' is now connected'}));
        }
    });
    client.on('disconnect',function(){
        client.broadcast(JSON.stringify({ 'UserName': '', 'Message':client.sessionId + ' left the conversation'}));
    });

});

所有我回来的都是NaN

1 个答案:

答案 0 :(得分:1)

这里需要更多的背景信息。如果Response.UserID实际上是NaN,那么if语句的第一个条件是返回false并且永远不会执行。

event传递给邮件的JSON是什么?如果UserID实际上是一个数字,那将会回答。