2016-07-14 281 views
0

我使用Socket類將字節數組中的圖像數據發送到在同一臺PC上運行的第三方程序(所以我不必擔心連接問題)。由於我的應用非常簡單,因此我只使用同步send(bytes)函數,僅此而已。問題是,它運行速度很慢。如果我發送一張20kB的小圖片,它需要接近15ms,但是如果圖片足夠大--1.5mB,則需要接近800ms,這對我來說是不可接受的。我該如何提高插座性能?C#Socket.send非常慢

Socket sender = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); 
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
IPAddress ipAddress = ipHostInfo.AddressList[0]; 
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 3998); 
sender.Connect(remoteEP); 

byte[] imgBytes; 
MemoryStream ms = new MemoryStream(); 
Image img = Image.FromFile("С:\img.bmp"); 
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); 
imgBytes = ms.ToArray(); 
/*Some byte operations there: adding headers, file description and other stuff. 
They are really fast and add just 10-30 bytes to array, so I don't post them*/ 

DateTime baseDate = DateTime.Now; // Countdown start 

for (uint i = 0; i < 100; i++) sender.Send(byteMsg); 

TimeSpan diff = DateTime.Now - baseDate; 
Debug.Print("End: " + diff.TotalMilliseconds); 
// 77561 for 1.42mB image, 20209 for 365kb, 1036 for 22kB. 
+0

你可以顯示你發送圖像的方式嗎? – mxmissile

+0

更新了我的文章。 – JustLogin

+0

你是基準嗎?那就是,只有'sender.Send'? – Martijn

回答

1

問題是在另一邊。我使用CCV socket modification作爲服務器,看起來,該程序即使在接收圖片時也會執行大量操作。我用測試服務器應用程序(來自Microsoft的Synchronous Server Socket Example,並從中刪除了字符串分析)嘗試了我的代碼,因爲這一切都開始工作快近100倍。

1

這可以讀取一個大文件到存儲器流,將其複製到一個數組,然後重新分配該陣列與一些數據,這實際上會影響性能預先考慮它,而不是Socket.send()。

嘗試使用流流拷貝方法:

 Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
     IPAddress ipAddress = ipHostInfo.AddressList[0]; 
     IPEndPoint remoteEP = new IPEndPoint(ipAddress, 3998); 
     sender.Connect(remoteEP); 
     using (var networkStream = new NetworkStream(sender)) 
     { 
      // Some byte operations there: adding headers, file description and other stuff. 
      // These should sent here by virtue of writing bytes (array) to the networkStream 

      // Then send your file 
      using (var fileStream = File.Open(@"С:\img.bmp", FileMode.Open)) 
      { 
       // .NET 4.0+ 
       fileStream.CopyTo(networkStream); 

       // older .NET versions 
       /* 
       byte[] buffer = new byte[4096]; 
       int read; 
       while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0) 
        networkStream.Write(buffer, 0, read); 
       */ 
      } 
     } 
+0

謝謝你的回答,但它確實是'Socket.send()'殺死了性能。我已更新我的帖子,以使其明顯。 – JustLogin