问题描述
我怎么可以检测到客户端已经从我的服务器断开连接?
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; }
}
}
这篇关于即时检测来自服务器套接字客户端断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!