0

At the moment I have a websocket server that generates a uuid for every connection made to it and passes that onto the client, and on the client side I update a simple list with all the connections. I'd like to see the original connaction's list refreshed, let me illustrate what I mean:

  1. open a tab - the first client connects and I see my uuid on the list
  2. I open a new tab, connect to the websocket, I see the previously connected ID and the new ID
  3. Now, when I go back to tab 1, I don't see both connections, only the first one that was there. How can I refresh this list, in a way such that if a websocket connection made, this list of uuid's is refreshed for all the connected clients.

My code at the moment is the following:

server:

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});
});

client:

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>");
        });

(and of course: <ul id="players"></ul>)

4

1 回答 1

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>";
});
于 2013-05-02T00:56:39.320 回答