我有一個等待新的套接字連接的TcpListener。當一個新的連接建立時,來自遠程用戶的一些其他代碼服務消息。我會定期檢查新的連接,如果有新連接,則應刪除舊連接。如何斷開TcpClient以允許新連接?
以前我只是打開大部分工作正常的新連接。有時候,我會遇到問題,重新使用相同的端口,所以我認爲關閉連接會更好(我認爲這也應該給舊用戶一個指示,表明連接已經死掉)。
下面的代碼是我試圖做到這一點,但由於某種原因,Disconnect調用似乎無限期阻止。有沒有辦法阻止? ...或者我在這裏錯過了別的東西嗎?
while(1)
{
// FYI, m_server is a TcpListener^ and m_client is a TcpClient^
// Check for new client connections
if (m_server->Pending() == true)
{
if(m_stream != nullptr)
{
m_client->Client->Shutdown(SocketShutdown::Both); // Stop sending/receiving
m_client->Client->Disconnect(true); // Disconnect the underlying network stream
m_client->Client->Close(); // Disconnect the underlying network stream
m_client->Close();
delete m_client;
m_client = nullptr;
}
m_client = m_server->AcceptTcpClient(); //grab the TCP client
m_stream = m_client->GetStream(); //create the stream at the same time
}
// ...go and service pending messages on the client stream
}
The docs on the Disconnect() function暗示有一個超時我可以設置,但他們沒有提到如何?
如果您需要致電斷開連接而不首先調用shutdown,您可以設置DontLinger Socket選項設置爲false,並指定一個非零的超時間隔,以確保數據排隊傳出傳輸發送。然後斷開連接,直到發送數據或直到指定的超時到期。如果將DontLinger設置爲false並指定零超時間隔,則Close會釋放連接並自動丟棄傳出的排隊數據。
[編輯]我找到了解決的超時問題,通過改變m_client->Client->Disconnect(true);
到m_client->Client->Disconnect(false);
但仍然沒有提醒我的客戶套接字已經關閉。我用盡了一切我能想到的測試,但他們都成功:
// m_client is a TcpClient^
bool stillConnected = ((m_client != nullptr) &&
(m_client->Connected == true) &&
(m_client->Client != nullptr) &&
(m_client->Client->Connected == true));
stillConnected
始終是真實的,即使接連客戶端已連接到服務器,並因此被稱爲全部關閉點點滴滴以上。這就像我在我的問題的頂部提到的關閉的東西沒有正確地關閉套接字或什麼東西?
這是C++/CLI ?,不是嗎? – abatishchev 2011-01-28 10:20:22
是的,但我相信這個問題是與.NET/Windows網絡,而不是我用來與底層硬件進行交互的語言。 – 2011-01-28 10:26:32