Reputation: 5532
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?
Upvotes: 4
Views: 5067
Reputation: 55359
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.
Upvotes: 3