目前我有一个websocket服务器,为每个连接生成一个uuid并将其传递到客户端,在客户端,我更新一个包含所有连接的简单列表。我希望看到最初的connaction列表刷新,让我说明一下我的意思:
目前我的代码如下:
服务器:
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>
)
答案 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>";
});