简体   繁体   中英

How to ensure NetworkStream to send data immediately without closing the Stream or TcpClient?

I have a very simple code snippet that tries to send data via TcpClient and its associated 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);

I've found that usually the data won't be sent immediately after stream.Write() . If I add client.Close() or stream.Close() then data will be sent. However, in my case, I'm trying to wait for the server to send some ACK message back so I want to reuse the original NetworkStream without closing either the TcpClient or NetworkStream . How can this be done?

Set TcpClient.NoDelay to true so that Nagle's algorithm isn't used.

From the MSDN Library documentation:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM