C#Socket.send非常慢

时间:2016-07-14 13:39:24

标签: c# performance sockets bytearray

我使用Socket类将字节数组中的图像数据发送到在同一台PC上运行的第三方程序(因此我不必担心连接问题)。由于我的应用程序非常简单,因此我只使用同步send(bytes)函数,仅此而已。问题是,它运行得很慢。如果我发送一个小的20kB图片,它需要大约15ms,但如果图片很大--1.5mB,它需要近800ms,这对我来说是不可接受的。如何提高套接字性能?

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.

2 个答案:

答案 0 :(得分: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);
                */
            }
        }

答案 1 :(得分:1)

问题出在另一边。我使用CCV socket modification作为服务器,看起来这个程序即使在接收图片时也会进行大量操作。我已经尝试使用测试服务器应用程序(Microsoft Synchronous Server Socket Example并从中删除了字符串分析)来解决我的代码问题,因此一切都开始快了近100倍。