我创建了一个nodejs游戏。我在服务器上有一个setInterval函数,它发送播放器附近的所有对象。但它似乎并不像我在本地运行时那样顺畅。数据包有大约60个对象。这是用于发送对象并在客户端上接收它们的服务器代码。任何压缩包装或减少滞后的方法? pinka.herokuapp.com
服务器:
setInterval(function() {
server.update();
for(var key in sockets) {
var socket = sockets[key];
var player = server.players.filter(function(p) {
return p.id == socket.id
})[0];
var package = [];
var blobs = server.getNodesInRange(player.centerX, player.centerY);
for(var i = 0; i < blobs.length; i++) {
var b = blobs[i];
package.push({
x: b.x,
y: b.y,
nick: b.nick,
size: Math.sqrt(b._mass) * 10,
hue: b.hue
});
};
socket.emit("update blobs", package);
socket.emit("leaders", server.getLeaders());
if(player.blobs.length == 0) {
socket.emit("dead");
continue;
}
var translateX = player._centerX * player._drawZoom - player.screenWidth / 2;
var translateY = player._centerY * player._drawZoom - player.screenHeight / 2;
socket.emit("center and zoom", {
centerX: translateX,
centerY: translateY,
zoom: player._drawZoom
});
}
}, 1000/60);
客户:
socket.on("update blobs", function(data) {
blobs = data;
});
这是整个沟通部分。
答案 0 :(得分:2)
正如Jonas W.所说,问题在于服务器 - 客户端通信。 为了提高效率,socket.io的实时系统应该基于事件而不是间隔检查。
我建议你有这样的事情:
伪代码示例:
客户端
let updating = false;
let timeout = 0;
// Assuming this function is triggered everytime the user moves (i.e. presses a key)
onUserMove (data) {
if ('same press as before' && updating) {
// ignore move if it's the same that has just been done
return;
} else {
socket.emit('user:move', data);
// 'Block' the emit for same movement for 20ms
updating = true;
clearTimeout(timeout);
timeout = setTimeout(() => {
updating = false;
}, 20);
}
}
服务器
socket.on('user:move', (data) => {
const dataForTheUser = processingYouAreAlreadyDoing(data);
socket.emit('data:for:user', dataForTheUser);
// In case there's information to be sent to every user
const dataToBroadcast = getDataToBroadcast(data);
const usersToBroadcast = getCloseUsers(data);
for (let user in usersToBroadcast) {
user.socket.emit('whatever:event', dataToBroadcast);
}
})