我知道,这里已经有很多类似的问题,但我没有找到让它更快的解决方案或者为什么它这么慢的原因?
我们在 C#.NET 中有一个应用程序需要通过 TCP 与响应同一 TCP 流(全部以字节为单位)的设备进行通信。消息的发送速度非常快(大约 20 毫秒),但是当我们使用 NetworkStream.Read() 方法(或类似的 Socket.Receive())从 TCP 套接字读取数据时,大约需要 600 毫秒。我通过在 Read 方法之前启动秒表并在 Read 之后立即停止来获得这个数字。
我还使用 Wireshark 记录流量,在那里我看到通信进行得非常快(使用 TCPNoDelay 和 TCPAckFrequency 注册表黑客)但是我看到发送到设备的以下消息是在 600 毫秒之后(在读取之后)上一个答案)。
设备无法同时处理多条消息,它们还会使用自定义的确认进行应答,以便我们的程序知道最后发送的消息已被正确接收和构建。
好的,这是我为控制台应用程序准备的一些测试代码,甚至还有读取延迟 600 毫秒的问题。
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();
}
结果如下:读取速度为 500,写入速度为 0
最佳答案
我刚刚找到了解决我的网络速度慢问题的方法,我想与大家分享。您永远不知道什么时候或谁会遇到同样的问题。
今天早些时候我来到这个网站TcpClient receive delay of over 500ms在那里我遵循了 PSH 位 (IgnorePushBitOnReceives) 的注册表黑客的解决方案并解决了它。所以我们现在有了临时的快速通信,因为我认为我们正在使用的硬件人员只需要设置 TCP 消息的 Push 标志。
关于c# - 为什么 NetworkStream.Read 这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9682370/