socket.io刷新连接客户端的列表

时间:2013-05-02 00:16:08

标签: javascript node.js websocket socket.io

目前我有一个websocket服务器,为每个连接生成一个uuid并将其传递到客户端,在客户端,我更新一个包含所有连接的简单列表。我希望看到最初的connaction列表刷新,让我说明一下我的意思:

  1. 打开一个标签 - 第一个客户端连接,我看到了我的uuid 列表
  2. 我打开一个新标签,连接到websocket,我看到了 先前已连接的ID和新ID
  3. 现在,当我回到标签时 1,我没有看到两个连接,只有第一个连接。 如何刷新此列表,如果是websocket 连接完成后,这个uuid的列表会为所有人刷新 连接客户。
  4. 目前我的代码如下:

    服务器:

    var http = require("http"), io = require("socket.io"), uuid = require ("node-uuid");
    var connectedPlayers = new Array();
    var server = http.createServer(function(req, res) { 
      // Send HTML headers and message
      res.writeHead(200,{ "Content-Type": "text/html" }); 
      res.end("<h1>Server is ready & listening</h1>");
    });
    server.listen(1222, "1.1.1.1");
    
    var socket = io.listen(server);
    socket.set('log level', 0);
    
    socket.on("connection", function(client) {
      client.on("connection", function(){
        console.log("Client connected.");
      });
    
      client.on("disconnect",function(client){
        //connected--;
        console.log("Client disconnected.");
      });
    
      client.userid = uuid();
      console.log(client.userid);
      connectedPlayers.push(client.userid);
      client.emit("onconnected", {playersId: connectedPlayers});
    });
    

    客户端:

    var socket = io.connect("1.1.1.1:1222");
    
            console.log(socket);
            socket.on("connect",function() {
                console.log("Client has connected to the server");
            });
    
            socket.on("disconnect",function() {
                console.log("The client has disconnected from the server");
            });
    
            socket.on("error", function(message) {
                console.log("It is not possible to connect to the server: " + message);
            });
    
            socket.on("onconnected", function(data) {
                for (var i = 0; i < data.playersId.length; i++)
                    $("#players").append("<li>" + data.playersId[i] + "</li>");
            });
    

    (当然还有<ul id="players"></ul>

1 个答案:

答案 0 :(得分:1)

您需要使用'io.sockets.emit'而非'client.emit'发出事件。

更改服务器脚本中的最后一行:

  client.emit("onconnected", {playersId: connectedPlayers});

为:

  socket.sockets.emit("onconnected", {playersId: connectedPlayers});

要在列表中添加值,我的方式如下:

socket.on("onconnected", function(data) {
    var tmp = document.getElementById("players");
    for (var i in data.playersId)
        tmp.innerHTML += "<li>" + data.playersId[i] + "</li>";
});