当远程端点没有连接c#时,TCP可能会失败

本文关键字:TCP 失败 连接 程端点 端点 | 更新日期: 2023-09-27 18:07:57

使用。net sockets。我正在尝试确定套接字是否连接。如果远程端点没有连接,我希望发送操作失败。实际上,我不会在发送上得到异常,但是发送成功通过后,一段时间后发送将失败。对此有什么解释吗?我还能做些什么来获得连接状态?

我的代码很简单基于此'

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();    `

当远程端点没有连接c#时,TCP可能会失败

TCP中没有"连接状态"。检测连接断开的唯一可靠方法是尝试反复写入:最终连接断开将导致ECONNRESET或在编程语言中映射到的任何东西。您还应该在读取时使用读超时,其值是最长请求的预期延迟的两倍,并将其视为断开的连接或至少是断开的事务,但如果事务延迟变化很大,则这是有问题的。