我已經在一個套接字庫上做了一些工作,它在過去的一年中用於在.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