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

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

问题描述

我怎么可以检测到客户端已经从我的服务器断开连接?

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

我有以下的code在我的 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);
}

我需要找到一种方法,尽快客户端已经从处理插座断开探索。

我已经试过:

  1. handler.Available;
  2. handler.Send(新字节[1],0, SocketFlags.None);
  3. handler.Receive(新字节[1],0, SocketFlags.None);
  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.

任何帮助将AP preciated。

Any help will be appreciated.

推荐答案

由于没有可用时,插座断开信号的事件,你将有一个频率是可以接受你轮询它。

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