node.js sockets.io每隔约25秒断开连接(与心跳相关)

时间:2012-03-05 09:55:10

标签: node.js socket.io heartbeat

我正在尝试使用socket.io设置node.js服务器。我看到的问题是我的服务器每25秒断开连接+重新连接客户端。

这是我的服务器代码:

var io = require('socket.io').listen(5876);
io.sockets.on('connection', function (socket)
{
    console.log("New connection established");

    socket.on('disconnect', function()
    {
        console.log("A client has disconnected.");
    });
}

我的客户端使用socket.io.js分发进行连接。据我所知(显然不正确),我需要我的客户端每隔15秒发送一次“心跳”(消息“:: 2”),以防止服务器认为连接已死并断开连接。基本上是:

<script src="socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost:5876');

    socket.on('connect', function(data)
    {
        console.log("Connected to server.");
        setInterval(function() { socket.emit("::2"); console.log("sent heartbeat"); }, 15000); // schedule a heartbeat for every 15 seconds
    });
</script>

但是客户端仍然每隔25秒就会断开连接+重新连接(不包括前25秒钟)。

node.js服务器控制台日志看起来像这样(可能已经删除了一些早期相同的连接/断开阶段,因为它每25秒回显一次):

New connection established
   debug - emitting heartbeat for client 652791160849839915
   debug - websocket writing 2::
   debug - set heartbeat timeout for client 652791160849839915
   debug - got heartbeat packet
   debug - cleared heartbeat timeout for client 652791160849839915
   debug - set heartbeat interval for client 652791160849839915
   info  - transport end
   debug - set close timeout for client 652791160849839915
   debug - cleared close timeout for client 652791160849839915
   debug - cleared heartbeat interval for client 652791160849839915
A client has disconnected.
   debug - discarding transport
   debug - client authorized
   info  - handshake authorized 5961067041159055274
   debug - setting request GET /socket.io/1/websocket/5961067041159055274
   debug - set heartbeat interval for client 5961067041159055274
   debug - client authorized for
   debug - websocket writing 1::
New connection established

如何阻止服务器每隔25秒断开连接+重新连接客户端?

2 个答案:

答案 0 :(得分:9)

您使用的是最新版本的socket.io,0.9.1 / 0.9.1-1吗?如果是这样,这是Guillermo确认的已知问题。目前的建议是回滚到0.9.0或0.8.7

https://github.com/LearnBoost/socket.io/issues/777

答案 1 :(得分:2)

你不需要发送心跳来保持套接字连接,socket.emit的语法也是

          socket.emit('event_name',{"data"});