簡體   English   中英

為什么NetworkStream.Read這么慢?

[英]Why is NetworkStream.Read so slow?

我知道,這里已經有很多類似的問題,但是我沒有找到使它更快的解決方案,或者它為什么這么慢?

我們在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();
}

因此,結果如下: The reading speed is 500 and the writing speed is 0

我剛剛找到了解決網絡緩慢問題的解決方案,並希望與大家分享。 您永遠不知道何時或誰可能遇到相同的問題。
今天早些時候,我來到這個站點, TcpClient接收到500ms以上的延遲,然后我按照PSH位(IgnorePushBitOnReceives)的注冊表hack的解決方案進行了解決。 現在我們有了暫時的快速通信,因為我認為我們所使用的硬件的人們只需要設置TCP消息的Push標志。

我想您可以在這里找到答案:

NetworkStream讀取速度慢

只需嘗試更改緩沖區大小,它應該可以更快地工作。

您還應該嘗試使用Microsoft網絡監視器來查看問題背后發生的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM