Skip to main content
 首页 » 编程设计

c#之如何保证NetworkStream在不关闭Stream或TcpClient的情况下立即发送数据

2024年08月06日30thcjp

我有一个非常简单的代码片段,它尝试通过 TcpClient 及其关联的 NetworkStream 发送数据。

var client = new TcpClient("xxx.xxx.xxx.xxx", 1234); 
NetworkStream stream = client.GetStream(); 
byte[] buffer = Encoding.ASCII.GetBytes(str); 
stream.Write(buffer, 0, buffer.Length); 

我发现通常不会在 stream.Write() 之后立即发送数据。如果我添加 client.Close()stream.Close() 然后将发送数据。但是,就我而言,我正在尝试等待服务器发回一些 ACK 消息,因此我想重用原始 NetworkStream 而无需关闭 TcpClient网络流。如何做到这一点?

请您参考如下方法:

设置TcpClient.NoDelaytrue 以便 Nagle's algorithm未使用。

来自 MSDN 库文档:

When NoDelay is false, a TcpClient does not send a packet over the network until it has collected a significant amount of outgoing data. Because of the amount of overhead in a TCP segment, sending small amounts of data is inefficient. However, situations do exist where you need to send very small amounts of data or expect immediate responses from each packet you send. Your decision should weigh the relative importance of network efficiency versus application requirements.