发送两个数据包(一个有长度,一个有数据)或发送一个连接数据包?

时间:2011-09-20 21:10:36

标签: c#

哪个更好?

在每个代码之前假设此代码:

byte[] data = Encoding.ASCII.GetBytes("Test Packet Message");
byte[] header = BitConverter.GetBytes(data.Length);

clientStream.Write(header, 0, header.Length);
clientStream.Write(data, 0, data.Length);

B:

byte[] bytes = new byte[header.Length + data.Length];

Buffer.BlockCopy(header, 0, bytes, 0, header.Length);
Buffer.BlockCopy(data, 0, bytes, header.Length, data.Length);

clientStream.Write(bytes, 0, bytes.Length);

A 的好处是不必将字节从一个阵列复制到另一个阵列,因此在CPU上更容易(客户端和服务器都必须发送和接收数据,因此 A如果发送大量数据,方法可能会更快。

B 只能发送一个数据包。人们谈论发送单个小包的开销。此外,Nagle的算法可能会使用 A ,如this post所示。

如果还有一种方法可以完成 A ,而不必将所有字节从数据库和数据数组复制到字节数组,那会有什么好处但是我不确定这是否可能..似乎有一种方法可以优化它/使其更有效但我不确定。

1 个答案:

答案 0 :(得分:0)

我希望接受多个缓冲区的以下方法可以实现您的目标。但是,我想测试一下,确定用数据包发送的确切内容。

//Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.
Socket.Send Method (IList<ArraySegment<Byte>>, SocketFlags)

请参阅以下帖子:

UDP - Can I send two datagram parts, and make the receiving end combine them into one?