Reputation: 1201
In my windows service I need to stream data to a tcp server. I declared a global TcpClient and NetworkStream and initiate them when the service starts. Every 30 seconds I go through an array of about 30-40 strings to send to the tcp server.
The send method looks like this:
private void sendMessage(string message)
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
Globals._stream.Write(data, 0, data.Length);
if (Globals._responseEnabled)
{
data = new Byte[256];
String responseData = String.Empty;
Int32 bytes = Globals._stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
if (Globals._logStream)
Globals._el.writeEventToWindowsLog("Received: " + responseData, "Info");
}
}
Problem is that every 30 seconds only a few packets are sent with all of the strings combined inside, I want the strings to be sent in one packet each.
So how do I get the NetworkStream.write method to send the packet immediately? If I declare a new TCPClient and NetworkStream each time I call the send method (about 60times per minute) the data is sent seperately, but thats not a very nice solution. I tried NetworkStream.flush but that wasnt working..
Upvotes: 2
Views: 3297
Reputation: 180897
You should set the NoDelay property on the TcpClient to true
;
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.
Since you're wrapping it in a stream, you may still need to flush the stream to send immediately.
Upvotes: 3