目前,我有一个websocket服务器,它为每个连接生成一个uid,并将其传递到客户端,在客户端,我更新了一个包含所有连接的简单列表。我希望看到原始连接的列表被刷新,让我来说明我的意思:
- 打开选项卡-第一个客户端连接,我看到我的uid在
- 我打开一个新的选项卡,连接到websocket,我看到先前连接的ID和新ID
- 现在,当我回到tab我没有看到两种联系,只有第一个联系。我如何刷新这个列表,以一种方式,如果一个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>
)
您需要使用'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>";
});