1

我正在尝试通过 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));
    }
};

并以堆栈溢出异常结束......

4

2 回答 2

1

我不想删除这个问题,但我承认我已经使用了一种解决方法,方法是在 C# dll 中使用 edge 创建一个辅助“GetTime”挂钩。

在 nodejs 方面,我只是设置了一个间隔并每 500 毫秒调用一次 GetTime 挂钩,现在一切似乎都在工作。

这绝对值得更多探索,但我现在要继续前进。

于 2015-07-06T18:53:16.533 回答
0

我会检查浏览器向服务于长轮询的服务器发出了多少并发请求。您可能会遇到并发连接限制。一旦超过该限制,后续请求将在客户端排队。在长轮询的情况下,可观察到的效果通常是您所描述的:长轮询需要很长时间才能完成,一旦完成,您会立即收到一批消息。

底线是我认为这与您使用 edge.js 无关,因为来自 C# 的回调出现及时。

于 2015-07-03T09:25:17.367 回答