我已经在一个套接字库上做了一些工作,它在过去的一年中用于在.NET中传输医学图像。早期,我们很难检测套接字何时关闭,但最终达到稳定的解决方案。
我们的应用程序使用NetworkStream来读取/写入套接字。我们有一个类似于您的线程,它是在新连接到达时创建的,用于读取和写入网络数据。我们调用下面的方法来轮询数据何时到达或连接何时关闭。如果您不想轮询,可以调整该方法以使用更长的超时时间。当我们知道数据可用时,我们从NetworkStream对象读取数据。
下面的关键点是零字节在套接字上发送,这似乎在套接字关闭时检测到,如注释中所述。 OnNetworkError方法仅用于启动正在关闭的线程。
史蒂夫
protected override bool NetworkHasData()
{
if (_socket == null)
return false;
// Tells the state of the connection as of the last activity on the socket
if (!_socket.Connected)
{
OnNetworkError(null, true);
return false;
}
// This is the recommended way to determine if a socket is still active, make a
// zero byte send call, and see if an exception is thrown. See the Socket.Connected
// MSDN documentation. Only do the check when we know there's no data available
try
{
List readSockets = new List();
readSockets.Add(_socket);
Socket.Select(readSockets, null, null, 100000);
if (readSockets.Count == 1)
{
if (_socket.Available > 0)
return true;
OnNetworkError(null, true);
return false;
}
_socket.Send(new byte[1], 0, 0);
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (!e.NativeErrorCode.Equals(10035))
OnNetworkError(e, true);
}
return false;
}
你能在这里发布一些代码,所以我们可以看到可能发生什么? – GEOCHET 2009-01-12 17:29:26