Node.js的 - Socket.IO 1.0 - 超时事件事件、js、Node、Socket

2023-09-07 09:50:54 作者:有几分喜欢就有几分甘愿

我使用Socket.IO(1.1.0的最新版本)与Android应用程序(客户端)交换消息。 我想设置超时(5S为例)来检查,如果我的客户端仍连接或没有(我想处理的Andr​​oid应用程序崩溃时的情况)。此外,我想,当出现超时,生成事件。 我想做的事情是这样的:

I'm using Socket.IO (the latest version 1.1.0) to exchange messages with an Android app (the client). I would like to set a timeout (5s for example) to check if my client is still connected or not (I would like to handle the case when the Android app crashes). Moreover, I would like to generate an event when a this timeout occurs. What I want to do looks like this:

1 /设置超时

var socket = require('socket.io')({
   //options go here
  'timeout': 5000 //set the timeout to 5s
});

2 /把手超时事件:

2/ Handle timeout event:

socket.on('timeout', function(){
   //my treatment
});

但我找不到任何实现来处理超时。

But I don't find any implementation to handle the timeout.

感谢您的帮助!

推荐答案

这不是什么超时设置手柄。超时是服务器将等待多长时间重新连接之前,眼泪就下来了该连接。你可能不希望设定它的短;甚至可能把它的默认值。

That's not what the timeout setting handles. The timeout is how long the server will wait for a re-connect before it tears down that connection. You probably don't want to set it that short; possibly even leave it at the default.

Socketio默认自动发送心跳。你真的应该只需要分配功能时,会收到在服务器端的断开消息到运行。

Socketio automatically sends heartbeats by default. You really should just need to assign a function to run when the 'disconnect' message is received on the server side.

io.on('connection', function(socket){
       console.log('a user connected');
       socket.on('disconnect', function(){
           console.log('user disconnected');
       });
});

看看这篇文章关于心跳的详细信息: Advantage/disadvantage使用socketio心跳

Check out this post for more information about the heartbeat: Advantage/disadvantage of using socketio heartbeats