2012-03-13 131 views
4

我知道,这里已经有很多类似的问题,但我没有找到一个解决方案,使其更快或者它如此缓慢的原因?NetworkStream.Read为什么这么慢?

我们在C#.NET中有一个应用程序,需要通过TCP与在同一个TCP流上回答的设备进行通信(全部以字节为单位)。发送消息的速度非常快(约20毫秒),但是当我们使用NetworkStream.Read()方法(或类似的Socket.Receive())从TCP套接字读取数据时,大约需要600ms。通过在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(); 
} 

这提供了以下结果:The reading speed is 500 and the writing speed is 0

+3

没有一行代码? – TomTom 2012-03-13 10:35:07

+1

mybe是缓慢写入流的设备? – 2012-03-13 10:36:17

+0

我认真地怀疑你会通过查看流阅读代码来找到它。关注程序的其余部分,尤其是启动线程池线程的任何代码。一个快速测试是调用ThreadPool.SetMinThreads()并传递一个大数字。 – 2012-03-13 11:39:06

回答

2

我刚刚找到解决方案,以解决我的慢网络问题,我想与大家分享。你永远不知道什么时候或谁会遇到同样的问题。
今天早些时候,我来到这个网站TcpClient receive delay of over 500ms,在那里我遵循了PSH位(IgnorePushBitOnReceives)的注册表解决方案,并解决了它。所以我们现在暂时快速的通信回来了,因为我认为我们正在使用的硬件人员只需要设置TCP消息的Push标志。

0

我想你能在那里找到答案:

NetworkStream Read Slowness

只是试图改变缓冲区的大小,它应该工作得更快。

您还应该尝试使用Microsoft网络监视器来查看您的问题背后发生了什么。

+0

如果我没有错,Wireshark和Microsoft Network Monitor是一样的吗?还是它真的显示更多? – TimVK 2012-03-13 15:22:31