我正在关注 this制作 HTML5 游戏的教程。我想尝试混合 Node 以使其成为多人游戏。我在服务器上使用 node.js(v0.10.4),在前端使用 crafty.js。
我正在使用 socket.io 发送和接收消息。现在只有我一个人(不是多个客户)。发生的奇怪事情是来自服务器的消息似乎被发送了多次。我在 socket.io 中打开了 Debug模式,但它似乎只发送了一次数据,但在前端,数据似乎成倍地传入。我在数据上设置了一个增量器,看起来好像增量器没有递增多次,而是我得到了相同数据的多个副本。
这里是 Node 代码:
var http = require('http').createServer(handler),
static = require('node-static'),
io = require('socket.io').listen(http);
io.set('log level', 3);
http.listen(80);
//attach the socket to our server
var file = new static.Server(); //Create a file object so we can server the files in the correct folder
function handler(req, res) {
req.addListener('end', function() {
file.serve(req, res);
}).resume();
}
io.sockets.on('connection', function (socket) { //listen for any sockets that will come from the client
socket.on('collected', function(data) {
/**** here's where the data is being sent back to the client *****/
socket.emit('messageFromServer', { data: data.number });
});
});
这是前端代码:
//messenger entity
Crafty.c('SendRecieveMessages',{
count: 0,
sendMessageToServer : function() {
console.log('got a village');
/**** Here's where we send the message to the server ****/
socket.emit('collected', { village : "The message went to the server and back. it's collected", number : this.count });
this.count++;
},
recieveMessageFromServer : function() {
socket.on('messageFromServer', function(data) {
/*** This data seems to be coming back or logging multiple times? ***/
console.log(data);
});
}
});
最后是调试过程的屏幕截图。如您所见,数字并不总是递增,它看起来就像数据正在存储。谢谢!
最佳答案
看起来每次您调用 Crafty.c
时,recieveMessageFromServer()
也会被调用。每次调用 recieveMessageFromServer
时,它都会在套接字上附加一个额外的事件监听器。这就是为什么第一次返回数据时你会得到一个副本,然后第二次你会得到两个,第三次你会得到三个,依此类推。
您要么需要防止 recieveMessageFromServer
被多次调用,要么使用 removeListener或 removeAllListeners删除以前附加的监听器。
关于node.js - socket.io 数据似乎被发送了多次(nodejs 和 craftyjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17055153/