开发者

How do I find a node.js websocket message's connection?

I was writing the following code for a node.js websocket chat server, and was wondering what the variable lifetime issues around conn are.

// chat-server.js
// Joshua Marshall Moore
// 12/20/2010

var ws = require("../../lib/ws/server");
var server = ws.createServer();

conns = [];
server.addListener("connection", function(conn){
    function runHandler(msg){
        server.broadcast(JSON.stringify({"who": conns[conn], "when": Date.now(), "what": msg}));
    }

    function setupHandler(msg){
        if(conns.indexOf(msg)==-1 && msg!="Server"){
            // name has not been taken yet
            conns[conn] = msg;
            conn.send("name ok");

            server.broadcast(JSON.stringify({
                "who": "Server", 
                "when": Date.now(),
                "what": msg + " has joined us"
            }));

            conn.removeListener("message": setupHandler);
            conn.addListener("message": runHandler);
            return;
        }

        conn.send("name taken");
    }

    conn.addListener("message", setupHandler);
});

server.addListener("close", function(conn){
    server.broadcast(JSON.stringify({
        "who": "Server",
        "when": Date.now(),
        "what": conns[conn] + " has left us."
    }));

    delete conns[conn];
});

server.listen(16007);

The code above will run. A server connects, submits a name until the server says it's ok. any message sent from client to server is relayed to all clients.

I was trying to use the connection as a key to later retrieve the name submitted by the client earlier. However, when a second client connects, all messages are displayed as being from the last person to connect.

I was hoping someone here had some insight as the conn variable's scope throughout its life. From the looks of it, conn is local to the anonymous function registered for the server connection event. Therefore the functions defined inside of that anonymous function have themselve开发者_运维百科s access to conn.

My more specific question is this: the anonymous function is called each time a new connection is made. Does that mean that each time that happens, the functions setupHandler and runHandler use the copy of conn corresponding to the new connection they were called for, or is there chance for them to mix each other up?


@Ivo is right about the fact that u can't use objects as keys.

However, the issue is, as you pointed out, definitely with the scope. The conn in setupHandler is the last connected client. Why don't you do something like this:

server.addListener("connection", function(conn){
    conn.addListener("message", function(msg){
        if(conn.connected_username !== msg && msg!="Server"){
            if(conn.isRegistered === true) {
              server.broadcast(JSON.stringify({"who": conn.connected_username, "when": Date.now(), "what": msg}));
            } else {
              // name has not been taken yet so assign it!
              conn.connected_username = msg;
              conn.send("name ok");

              server.broadcast(JSON.stringify({
                "who": "Server", 
                "when": Date.now(),
                "what": msg + " has joined us"
              }));

              conn.isRegistered = true;
            }
            return;
        }

        conn.send("name taken");
    });
});

server.addListener("close", function(conn){
    server.broadcast(JSON.stringify({
        "who": "Server",
        "when": Date.now(),
        "what": conn.connected_username + " has left us."
    }));
});

server.listen(16007);

Why are you trying to complicate things? :)

Edit: After going through your code again, I realized that you are using listeners to distinguish between user registration and message. Made changes to the code.


You can't use objects as keys in JavaScript, all that [conn] does is to call toString() on conn. And hardly anyone out there overwrites toString() to return something useful.

So what does toString() return by default? Well for Objects it returns [object Object].

conn should have a id property, that will give you a unique value to use as a key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜