I know there are already many similar questions here, but I did not find a solution to make it faster or the reason why it is so slow?
We have a C # .NET application that must communicate via TCP with a device that responds in the same TCP stream (all in bytes). Sending messages is pretty fast (about 20 ms), but when we read data from a TCP socket using the NetworkStream.Read () method (or similar Socket.Receive ()), it takes about 600 ms. I get this number by starting the stopwatch before the Read method and stopping it right after Read.
I also register traffic with Wireshark, and there I see that the connection is pretty fast (using the TCPNoDelay and TCPAckFrequency hackers), but there I saw that the next message was sent to the device after 600 ms (after reading the previous answer).
Devices cannot process several messages at once, and they also respond with a confirmed Acknowledge so that our program knows that the last sent message was received and configured correctly.
Well, here is some kind of test code that I have for a console application, and even this is a problem with a delay of 600 ms when reading.
try { if (!retry) { Console.WriteLine("Please enter the IP address you want to check:"); ip = Console.ReadLine(); Console.WriteLine("Please enter the port where you want to check on:"); port = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Connecting to {0}: {1}", ip, port); Console.WriteLine("Please enter the message you want to write to the specified port:"); message = Console.ReadLine(); } tcp = new TcpClient(ip, port); tcp.NoDelay = true; tcp.Client.NoDelay = true; Stopwatch sWrite = new Stopwatch(); Stopwatch sRead = new Stopwatch(); Stopwatch sDataAvailable = new Stopwatch(); using (NetworkStream ns = tcp.GetStream()) { Byte[] data = System.Text.Encoding.ASCII.GetBytes(message + "\r"); sWrite.Start(); ns.Write(data, 0, data.Length); sWrite.Stop(); data = new byte[256]; sRead.Start(); Console.WriteLine("There is data on the socket: {0}", ns.DataAvailable); int readBytes = ns.Read(data, 0, data.Length); sRead.Stop(); message = System.Text.Encoding.ASCII.GetString(data, 0, readBytes); Console.WriteLine(message); } Console.WriteLine("The reading speed is {0} and the writing speed is {1}", sRead.ElapsedMilliseconds, sWrite.ElapsedMilliseconds); } catch { } finally { tcp.Close(); }
And this gives the following result: The reading speed is 500 and the writing speed is 0
TimVK source share