如何使用Node.js检测客户端Internet断开连接

Lij*_*mas 0 disconnect node.js node.js-stream

我正在使用node.js作为游戏服务器.

这是我的服务器脚本

 var net = require('net');
 var http = require('http');

var host =  '192.168.1.77';
var portNum = 12345;//


  function policy() 
{
    var xml = '<?xml version="1.0"?>\n<!DOCTYPE cross-domain-policy SYSTEM' +
            '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">\n<cross-domain-policy>\n';

    xml += '<allow-access-from domain="*" to-ports="*"/>\n';
    xml += '</cross-domain-policy>\n\0' + "\0";
    return xml;
}



var server = net.createServer(function (stream) 
{
stream.setEncoding('utf8');

stream.on('data', function (data) { 

    if (data == '<policy-file-request/>\0') 
    {
        var x = policy();
        stream.write(x);
        var server_date = new Date();
        var serv_sec = server_date.getSeconds();
        return;
    }

    var comm = JSON.parse(data); 
    if (comm.action == "Join_Request"  && comm.gameId =="game1") // join request getting from client
    {
        var reply0 = new Object();
        reply0.message = "WaitRoom";
        stream.write(JSON.stringify(reply0) + "\0");   
     }
 });

stream.on('disconnect', function() 
{
    console.log("disconnect");
 });
stream.on('close', function ()  
{
console.log("Close");
}); 

 //stream.setNoDelay(true);
//stream.setKeepAlive(true, 200);
//stream.setTimeout(10, function(){
//  console.log('timeout');
//});
 stream.on('connect', function() {
 console.log('check 2', stream.connected);
 }   );
  stream.on('error', function () { 
  console.log("Error");
  }); // close function 

  });  // ===== create server end
  server.listen(portNum,host,{'heartbeat interval':1,  'heartbeat timeout' : 2}  );
Run Code Online (Sandbox Code Playgroud)

================================================== =============================================

客户端脚本

    using UnityEngine;
    using System.Collections;
    using System;
    using System.Xml;
    using System.Linq;
    using System.Threading;
    using Boomlagoon.JSON;
    using JsonFx.Json;
    using System.Net.Sockets;

                      try 
                        {

                            tcpClient.Connect (host,portNum);
                            serverStream    =  tcpClient.GetStream ();
                            serverStream.Flush ();

                            ThreadPool.QueueUserWorkItem( new WaitCallback( ReceiveFromServer ) );



                            isConnectionActive = true;
                            isReadyToJoinRoom = true;
                            connected = 1;
                            disconnected =0;
                            c_global.isClientConnectOn = false;
                            c_global.isClientDisconnectOn = false;

                        }
                        catch( ArgumentException l_exception )
                        {
                            c_global.isClientDisconnectOn = true;
                            isConnectionActive = false;
                        }

                        catch( SocketException l_exception )
                        {
                            c_global.isClientDisconnectOn = true;
                            isConnectionActive = false;
                        }

                        catch(Exception e)
                        {
                            c_global.isClientDisconnectOn = true;
                            isConnectionActive = false;
                            connected = 0;
                            disconnected =1;

                        }


               public void ReceiveFromServer(object stateInfo) // Please call this function once
                {
                    print (" $$$$$$$$$$$ ReceiveFromServer  and isConnectionActive"+isConnectionActive);

                    while(isConnectionActive) // receive message continuously 
                    {
                        try
                        {
                            byte [] inStream = new byte[tcpClient.ReceiveBufferSize];

                            serverStream.Read (inStream,0,(int)tcpClient.ReceiveBufferSize);
                            string returnData = System.Text.Encoding.UTF8.GetString(inStream);

                            print ("*^^^^^^^^^^* returnData"+returnData);
                            Decide_Action(returnData);


                        }
                        catch (Exception e)
                        {
                            c_global.isClientDisconnectOn = true;
                        }


                    }

                }



           public void Decide_Action(string returnData)
           {
           try
           {

           var r_Msg = JSONObject.Parse(returnData); // recieved message r_Msg

           string msg = r_Msg.GetString("message") ;

           print ("Message = "+msg);

           switch(msg ) // check the action to do
           {
           case "Players_List":
           break;
           }

           }

           catch (Exception e)
           {
                            c_global.isClientDisconnectOn = true;
           }


           }
Run Code Online (Sandbox Code Playgroud)

当游戏关闭或退出游戏时,客户端断开连接检测服务器.那就是"关闭"功能,"错误"功能就是调用那个时间.

但是当互联网断开与客户端系统或设备的连接时,那个时间"关闭"功能或"错误"功能不会调用.

如何检测这种客户端断开连接

Node.js服务器未检测到客户端网络断开连接.

如果有人知道解决方案,请帮助我.

Bra*_*rad 7

无法区分丢失的连接和空闲连接.

至少,没有直接没有一些修改......

即使没有数据发送,TCP连接也可以存活.完全可以立即建立连接,12小时不发送任何内容,稍后再发送数据.服务器应该假设连接不再存在吗?根据设计,除非存在传输故障,否则它将假定存在连接.也就是说,如果数据被发送,并且没有ACK,连接最终将被关闭,相应的事件触发.

解决方案是使用TCP keepalive. 如果您调用socket.setKeepAlive(true, 10000),则启用keepalive探测数据包(实际上是具有0字节数据有效负载的TCP数据包)在空闲插槽10秒后发送到空闲插槽.远程系统将确认这些数据包.如果没有,则最终假定连接丢失,并且您正在寻找的事件将被触发.

更多信息: