如何检测套接字C#断开连接? [英] How to detect a disconnected socket C#?
问题描述
我一直在使用C#编写套接字客户端程序,并且想知道如何检测套接字的另一端何时不正常地"断开自身的连接,例如在拔出网络电缆或进行硬重置时.
I've been working on a socket client program in C# and am wondering how to detect when the other end of a socket has disconnected itself "ungracefully" as in a network cable being unplugged or a hard reset.
我下面有这些功能来访问套接字,并根据SO问题 MSDN文章,检查套接字是否断开连接的最佳方法是发送长度为0的1字节消息.如果引发异常并且WSAEWOULDBLOCK不是错误代码,则插座已断开连接.我已经尝试过了,但是在硬重置服务器连接后,客户端将调用 Send(new byte [1],0,0,SocketFlags.None)
并成功返回,而 Receive()
命令此后立即返回WSAEWOULDBLOCK错误.
I have these functions below to access the socket and according to the SO question here and this MSDN article, the best way to check for a disconnected socket is to send a 1-byte message with a length of 0. If an exception is thrown and WSAEWOULDBLOCK is not the error code then the socket is disconnected. I have tried this but after hard reseting the server connection the client will call Send(new byte[1], 0, 0, SocketFlags.None)
and return successfully and the Receive()
command right afterwards returns the WSAEWOULDBLOCK error.
有什么作用?
这是下面的代码. _socket
设置为非阻止模式:
Here's my code below. _socket
is set to non-blocking mode:
private int nonBlockRecv(byte[] recvBytes, int offset, int size, SocketFlags sf)
{
int bytesRecv = 0;
while (true)
{
try
{
nonBlockSend(new byte[1], 0, 0, sf);
bytesRecv = _socket.Receive(recvBytes, offset, size, sf);
break;
}
catch (SocketException excp)
{
if (excp.ErrorCode != 10035) // WSAEWOULDBLOCK
throw excp;
}
}
return bytesRecv;
}
private int nonBlockSend(byte[] sendBytes, int offset, int size, SocketFlags sf)
{
int bytesSent = 0;
while (true)
{
try
{
_socket.Send(sendBytes, offset, size, sf);
break;
}
catch (SocketException excp)
{
if (excp.ErrorCode != 10035) // WSAEWOULDBLOCK
throw excp;
}
}
return bytesSent;
}
这可能是有好处的,但是服务器是Windows Mobile设备.我在另一个线程中读到,不同的操作系统可能快要死了,就可以发送套接字关闭信号.也许Windows Mobile OS不会这样做?
This may be beneficial but the server is Windows Mobile device. I read in another thread that different OSs maybe able to send socket close signals when they're dying. Perhaps the Windows Mobile OS does not do this??
推荐答案
如果远程计算机正常断开会话连接,则 Socket.Receive()
方法将返回0个字节.您必须检测到知道远端已断开连接:
If the remote computer gracefully disconnects the session, the
Socket.Receive()
method will return with 0 bytes. You must detect that
to know that the remote end has disconnected:
int recv = sock.Receive(data);
if (recv == 0)
{
// Remote client has disconnected.
}
else
{
// Remote client has sent data.
}
此外,即使出现 SocketException
,您也可以标识套接字断开连接的异常.
Also, even if there SocketException
arises you can identify the exception for socket disconnection.
希望这有助于解决您的问题.
Hope this helps solve your problem.
这篇关于如何检测套接字C#断开连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!