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

查看:189
本文介绍了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.

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

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});
    });

更多信息:

您可以在此处获取有关配置 socket.io 的更多信息.

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天全站免登陆