我正在尝试通过 node.js 和 sockets.io 构建实时游戏和流式更新到客户端。
我正在使用最新的 Chrome 浏览器,但我也尝试过 FF。
所有服务器端代码都正确记录到控制台,所以我知道那里的时机很好,但在客户端,消息似乎是以“块”而不是流的形式到达的。
服务器:
var util = require("util");
var io = require("socket.io");
var socket = io.listen(8000);
init () {
socket.sockets.on("connection", onSocketConnection);
};
function onSocketConnection(client) {
util.log("New player has connected: " + client.id);
client.on("disconnect", onClientDisconnect);
client.on("getMatchupUpdates", onUpdateMatchup);
};
/* I'm calling an edge.js function to perform game stuff with a callback
to a js function 'onUpdateTime' to update a game clock on the client browser*/
function onUpdateTime(data)
{
console.log(data);
socket.emit("update time", data);
}
console.log 在 500 毫秒时产生预期的输出:
{ gameID: 77, secondsRemaining: 10 }
{ gameID: 77, secondsRemaining: 10 }
{ gameID: 77, secondsRemaining: 9 }
{ gameID: 77, secondsRemaining: 9 }
{ gameID: 77, secondsRemaining: 8 }
....
所以我知道回调正在返回 node.js 服务器,但随后调用客户端:
function onUpdateTime(data) {
console.log("received Time Update: ");
console.log(data);
$('#clockTimer').text(data.secondsRemaining);
}
我收到“块”中的消息。数据以正确的格式通过,但 websockets 似乎又回到了轮询:
http://localhost:8000/socket.io/?EIO=3&transport=polling&t=1435865813074-17&sid=WaNEY1UQUdkx6RLfAAAA
控制台正确记录,但同样,以块而不是流的形式......
> HTML1.html:802 Object {gameID: 77, secondsRemaining: 7}
> HTML1.html:802 received Time Update:
> HTML1.html:803 Object {gameID: 77, secondsRemaining: 7}
> HTML1.html:802 received Time Update:
> HTML1.html:803 Object {gameID: 77, secondsRemaining: 6}
> HTML1.html:802 received Time Update:
> HTML1.html:803 Object {gameID: 77, secondsRemaining: 6}
有什么建议吗?想法?额外需求?
**更新:**我在这里添加了边缘调用:
//set up update callback
var payload = {
matchupID: data.id,
updateTime: function (input, callback) {
callback(null, onUpdateTime(input));
},
updateScore: function (input, callback) {
callback(null, console.log(input));
},
updateGameBoard: function (input, callback) {
callback(null, console.log(input));
}
};
GetUpdates(payload, function (error, result) {
if (error) throw error;
console.log(result);
});
值得注意的是,我还更改了代码以在回调中发出消息:
//set up update callback
var payload = {
matchupID: data.id,
updateTime: function (input, callback) {
callback(null, socket.emit("update time", input));
},
updateScore: function (input, callback) {
callback(null, console.log(input));
},
updateGameBoard: function (input, callback) {
callback(null, console.log(input));
}
};
并以堆栈溢出异常结束......