[英]Expect TCP to fail when the remote endpoint is not connected C#
使用.net套接字。 我正在嘗試確定套接字是否已連接。 因為沒有連接遠程端點,我希望發送操作會失敗。 實際上,我在發送時沒有遇到異常,但是發送僅在一段時間后才能成功通過,發送將失敗。 有什么解釋嗎? 為了獲得連接狀態,我還能做什么?
基於此`,我的代碼非常簡單
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(); `
TCP中沒有“連接狀態”。 檢測斷開的連接的唯一可靠方法是嘗試重復寫入:斷開的連接最終將導致ECONNRESET或您的編程語言中映射的任何內容。 您還應該在讀取時使用讀取超時,該讀取超時的值應為最長請求的預期延遲的兩倍,並將其視為斷開的連接或至少也斷開的事務,但是如果事務的延遲變化很大,這將成為問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.