为了帮助可能遇到此问题的其他人,我设计了一个锁定系统,以便服务器仅在套接字空闲时发布数据。
这意味着服务器仍然尽可能快地发布,它只是不会堆叠几个传出的数据请求。请注意,这仅在您的消息被丢弃并且您需要最新信息时才有效。这也意味着消息之间存在一些开销,因为客户端必须通知服务器它已准备好接收更多消息。
然而,这意味着我的应用程序保持最新,不会因请求堆积而落后,如果您在本地运行一个浏览器并通过网络运行另一个浏览器,这在之前很明显。
Server.js
var socket = ...; // Create socket
// Create my data, in my project this updates very quickly
// roughly 60 times per second
var my_data = ...;
// Initially set receiving to false as the socket
// has no outgoing data
socket.set('receiving', false);
// Listen for received event, this indicates
// that the client has received an update
// and is now ready to receive more
socket.on('received', function() {
socket.set('receiving', false);
});
// Function will be called repeatedly to send out data
function update() {
// Check if the socket is receiving any data
socket.get('receiving', function(receiving) {
if(!receiving) {
// Lock the socket from receiving future updates
// by setting the receiving variable to true
socket.set('receiving', true, function() {
// Now emit data
socket.emit('update', my_data);
});
}
});
setTimeout(update, 0); // Recursively call update
}
setTimeout(update, 0); // Start update
Client.js
var socket = io.connect();
socket.on('update', function(data) {
// Store the data for processing
// Tell the server we have received the data
socket.emit('received');
});