我正在尝试使用socket.io创建一个双人竞争迷宫游戏。为了确保两个玩家都获得相同的迷宫,我想向两个客户发送种子,然后客户端根据所述种子生成迷宫。但是,当第二个玩家加入时,只有第一个玩家(已经在房间里)才会收到排放物。
以下是相关的服务器端房间和种子排放代码:
// Find and join an unfilled room
var roomID = 0;
while (typeof io.sockets.adapter.rooms[roomID.toString()] !== 'undefined' && io.sockets.adapter.rooms[roomID.toString()].length >= 2)
roomID++;
socket.join(roomID.toString());
console.log('A user from ' + socket.conn.remoteAddress + ' has connected to room ' + roomID);
// Seed announcement
if (io.sockets.adapter.rooms[roomID.toString()].length == 2) {
var seed = Math.random().toString();
socket.in(roomID).emit('seed', seed);
console.log("announcing seed " + seed + " to room " + roomID);
}
socket.on('seedAck', function(msg) {
console.log(msg);
})
在客户端,我有一些代码用种子回复服务器,以确定他们是否正确接收种子。
socket.on('seed', function(msg) {
// Some other code here...
socket.emit('seedAck', 'client has recieved seed ' + msg);
});
这是服务器看到的内容:
A user from ::1 has connected to room 0
A user from ::1 has connected to room 0
announcing seed 0.936373041709885 to room 0
client has received seed 0.936373041709885
要验证只有已经在会议室中的客户端收到了种子,我刷新了第一个客户端,而这次只有第二个客户端收到了种子。
我相信正在发生的事情是服务器在第二个客户端准备好之前发送种子。但是,经过多次Google搜索后,我无法找到解决方案。我正在考虑向客户端添加一个按钮,要求用户先按下按钮(从而确保客户端准备就绪),但这需要一些繁琐的簿记。我也在考虑某种回调函数,但我还没有得出如何正确实现它的结论。
我是唯一可以选择在两个客户端准备就绪时手动跟踪,还是有更好的解决方案集成在socket.io中?
编辑:我尝试修改我的代码,以便它等待两个客户端在发送种子之前发送他们已准备好的消息。服务器端,我有这个:
socket.on('ready', function(msg) {
console.log(msg);
// Seed announcement
if (io.sockets.adapter.rooms[roomID.toString()].length == 2) {
var seed = Math.random().toString();
socket.to(roomID).emit('seed', seed);
console.log("announcing seed " + seed + " to room " + roomID);
}
});
虽然客户端,我现在有这个:
socket.on('seed', function(msg) {
// Some other code here ...
socket.emit('seedAck', 'client has received seed ' + msg);
});
socket.on('connect', function() {
socket.emit('ready', 'client is ready!');
});
但是,同样的问题仍然存在,如服务器输出所示:
A user from ::1 has connected to room 0
client is ready!
A user from ::1 has connected to room 0
client is ready!
announcing seed 0.48290129541419446 to room 0
client has received seed 0.48290129541419446
第二个客户仍然没有正确接收种子。
答案 0 :(得分:0)
对我编辑的服务器代码的一个小修改解决了这个问题:
socket.on('ready', function(msg) {
console.log(msg);
// Seed announcement
if (io.sockets.adapter.rooms[roomID.toString()].length == 2) {
var seed = Math.random().toString();
io.sockets.in(roomID.toString()).emit('seed', seed); // Modified line
console.log("announcing seed " + seed + " to room " + roomID);
}
});
此解决方案取自this SO question。