0

当第二个客户端加入/连接服务器时,我愿意div在第一个元素旁边创建一个新元素:

应用程序.js

...
io.on('connection', function(client){
    console.log("Client connected...");
    client.emit('add_player');
});
...

索引.ejs

...
server.on('add_player', function () {
        $(document).ready(function () {
            $('.field').append(player);
            });
        });
    });
...

我在每个浏览器上只得到一个元素。这就是我得到的:

测验

这就是我想要实现的目标。但是怎么做?

测验测验

4

1 回答 1

0

好吧,我认为这是因为您仅在当前连接到服务器的客户端上发出该功能。然后,当您获得新连接时,您将再次仅在当前客户端发出一个函数,而不为旧连接而烦恼,您也不会查看已完成多少先前连接并在当前客户端上多次发出该函数。相反,您只发射一次。

所以你需要的是你必须维护一个客户端数组,并在每个连接上将新客户端推送到数组中。

var clientArray = new Array();

在连接侦听器上,您需要进行以下修改

io.on('connection', function(client){
console.log("Client connected...");
for(i=0;i<clientArray.length;i++)
    clientArray[i].emit('add_player');     //emitting the function once to all ohter clients because a new client has been added

clientArray.push(client);                  // pushing the new client to the array
for(i=0;i<clientArray.length;i++)
    client.emit('add_player');            // emitting the function on the new client exactly equal to the number of client presently in the array
});
于 2013-06-19T07:19:07.453 回答