NodeJS + Socket.io连接丢失/重新连接? [英] NodeJS + Socket.io connections dropping/reconnecting?

查看:634
本文介绍了NodeJS + Socket.io连接丢失/重新连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在生产中,我有一个使用连接局部变量保存游戏状态的游戏.但是,我注意到,如果我在连接上闲置了一段时间,它将断开连接并重新连接,这将丢失当前状态.在本地主机上进行测试时,我从未注意到此行为.这是套接字连接的规范行为,还是导致连接断开的其他原因.

In production, I have a game which uses connection-local variables to hold game state. However I notice that if I idle for a certain time on the connection, it disconnects and reconnects which loses the current state. During my tests on a local host, I never noticed this behavior. Is this the norm behavior for socket connections or is something else causing the connections to drop.

如果是正常行为,通常如何处理?应该在全局范围内存储连接值,以便用户断开/重新连接时可以恢复它们吗?

If it is a normal behavior how is this typically handled? Should connection values be stored globally so they can be restored should a user drop/reconnect?

推荐答案

您的问题与套接字超时有关.如果某个套接字上没有任何活动,socket.io会自动将其关闭.

Your problem is around socket timeouts. If there's no activity on a certain socket, socket.io will close it automatically.

一个简单(漏洞修复)的解决方案是向连接的客户端发送心跳以创建活动并阻止套接字超时.

An easy (and hackish) fix is to send a heartbeat to the connected client to create activity and stop the socket from timing out.

服务器:

function sendHeartbeat(){
    setTimeout(sendHeartbeat, 8000);
    io.sockets.emit('ping', { beat : 1 });
}

io.sockets.on('connection', function (socket) {
    socket.on('pong', function(data){
        console.log("Pong received from client");
    });
}

setTimeout(sendHeartbeat, 8000);

客户:

socket.on('ping', function(data){
      socket.emit('pong', {beat: 1});
    });

更多信息:

您可以在此处获得更多信息.

Mark评论说,如果用户确实丢失了连接(由于互联网故障,连接断开了),您应该能够将用户恢复到其最后的状态.

Mark commented that if the user does lose the connection (connection drops on his end because of internet troubles), you should be able to restore the user to his last state.

为此,最好的方法是使用一种已经广泛使用的方法来存储用户数据,cookie和会话.

To do that, the best way would be to use a already widely used method for storing user data, cookies and sessions.

有关如何执行此操作的非常出色的教程,位于此处.尽管他使用express来设置cookie,但是您可以使用任何方法(我使用rails来完成).使用此方法,您可以将用户数据存储在cookie中,并在握手过程中获取它.您可以从那里使用socket.handshake.data访问数据.

An extremely well done tutorial on how to do this located here. Although he uses express to set cookies, you can do this using anything (I do it using rails). Using this method, you can store the user data in a cookie and fetch it during the handshake. From there you can just access the data using socket.handshake.data.

这篇关于NodeJS + Socket.io连接丢失/重新连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆