【发布时间】:2013-05-02 09:51:37
【问题描述】:
目前我有一个 websocket 服务器,它为每个连接生成一个 uuid 并将其传递给客户端,在客户端我更新一个包含所有连接的简单列表。我希望刷新原始连接列表,让我说明一下我的意思:
- 打开一个选项卡 - 第一个客户端连接,我看到我的 uuid 在 列表
- 我打开一个新选项卡,连接到 websocket,我看到 以前连接的 ID 和新 ID
- 现在,当我返回选项卡时 1,我没有看到两个连接,只有第一个连接。 如何刷新此列表,如果 websocket 建立连接后,此 uuid 列表将针对所有 连接的客户端。
我现在的代码如下:
服务器:
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>)
【问题讨论】:
-
把client.emit改成socket.emit或者broadcast()
-
我已更改为 socket.emit() 但我的客户端似乎没有收到任何内容,客户端永远不会调用“onconnected”函数。
标签: javascript node.js websocket socket.io