即时检测来自服务器套接字客户端断开连接

编程入门 行业动态 更新时间:2024-10-09 23:19:50
本文介绍了即时检测来自服务器套接字客户端断开连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

我已经试过:

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

    更多推荐

    即时检测来自服务器套接字客户端断开连接

    本文发布于:2023-11-23 13:14:21,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1621572.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:客户端   服务器

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!