2013-04-08 29 views
0

使用.net套接字。我正在嘗試確定套接字是否連接。 那裏我希望發送操作失敗,如果遠程端點沒有連接。 幾乎沒有發送異常,但發送成功後才發送失敗。 對此有任何解釋嗎? 我還能做些什麼才能獲得連接狀態?期望TCP在遠程端點未連接時失敗C#

我的代碼是在此基礎上 '

Int32 port = 13000; 
TcpClient client = new TcpClient(server, port); 

// Translate the passed message into ASCII and store it as a Byte array. 
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);   

// Get a client stream for reading and writing. 

//流stream = client.GetStream非常簡單 ();

NetworkStream stream = client.GetStream(); 

// Send the message to the connected TcpServer. 
stream.Write(data, 0, data.Length); 

Console.WriteLine("Sent: {0}", message);   

// Receive the TcpServer.response. 

// Buffer to store the response bytes. 
data = new Byte[256]; 

// String to store the response ASCII representation. 
String responseData = String.Empty; 

// Read the first batch of the TcpServer response bytes. 
Int32 bytes = stream.Read(data, 0, data.Length); 
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); 
Console.WriteLine("Received: {0}", responseData);   

// Close everything. 
client.Close(); ` 
+1

你能展示你的代碼嗎? TCP是一個可靠的協議,它會嘗試發送數據直到超時。我想你是在調整超時屬性後。 – oleksii 2013-04-08 13:04:42

+0

這有幫助嗎? http://stackoverflow.com/q/9707314/128217 – zimdanen 2013-04-08 14:11:33

回答

1

TCP中沒有'連接狀態'。檢測斷開連接的唯一可靠方法是嘗試重複寫入:最終斷開的連接將導致ECONNRESET或任何在編程語言中映射的內容。在讀取時,您還應該使用讀取超時,其值爲最長請求的預期延遲的兩倍,並將其視爲斷開的連接或至少是已損壞的事務,但如果事務延遲變化很大,則會出現問題。