0

使用 .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.

// 流流 = 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();    `
4

1 回答 1

1

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

于 2013-04-09T00:28:41.163 回答