2013-04-08 28 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或任何在编程语言中映射的内容。在读取时,您还应该使用读取超时,其值为最长请求的预期延迟的两倍,并将其视为断开的连接或至少是已损坏的事务,但如果事务延迟变化很大,则会出现问题。