立即检测客户端与服务器套接字的断开连接 [英] Instantly detect client disconnection from server socket

查看:36
本文介绍了立即检测客户端与服务器套接字的断开连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测客户端与我的服务器断开连接?

How can I detect that a client has disconnected from my server?

我的 AcceptCallBack 方法中有以下代码

I have the following code in my AcceptCallBack method

static Socket handler = null;
public static void AcceptCallback(IAsyncResult ar)
{
  //Accept incoming connection
  Socket listener = (Socket)ar.AsyncState;
  handler = listener.EndAccept(ar);
}

我需要想办法尽快发现客户端已经与handler Socket断开连接.

I need to find a way to discover as soon as possible that the client has disconnected from the handler Socket.

我试过了:

  1. handler.Available;
  2. handler.Send(new byte[1], 0,SocketFlags.None);
  3. handler.Receive(new byte[1], 0,SocketFlags.None);

当您连接到服务器并希望检测服务器何时断开连接时,上述方法有效,但当您是服务器并希望检测客户端断开连接时,它们不起作用.

The above approaches work when you are connecting to a server and want to detect when the server disconnects but they do not work when you are the server and want to detect client disconnection.

任何帮助将不胜感激.

推荐答案

由于没有事件可用于在套接字断开连接时发出信号,因此您必须以您可以接受的频率对其进行轮询.

Since there are no events available to signal when the socket is disconnected, you will have to poll it at a frequency that is acceptable to you.

使用此扩展方法,您可以有一个可靠的方法来检测套接字是否断开连接.

Using this extension method, you can have a reliable method to detect if a socket is disconnected.

static class SocketExtensions
{
  public static bool IsConnected(this Socket socket)
  {
    try
    {
      return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
    }
    catch (SocketException) { return false; }
  }
}

这篇关于立即检测客户端与服务器套接字的断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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