【发布时间】:2015-05-19 23:32:05
【问题描述】:
我想通过 tcp 发送一个 int 列表(可以是 10 到 1000 个 int)
在解析数据之前,我会向客户端发送它应该接收多少字节。
我也使用 BeginSend / BeginReceive 模式(每个线程一个线程)。
我想出了这个简单的代码来做我想做的事
const int sizeOfInt = sizeof(int);
int index = 0;
var OriginalList = new List<int>();
OriginalList.Add(1);
OriginalList.Add(42);
//.....
OriginalList.Add(9001);
//prepare and send the ArrayOfByte over the wire
var ArrayOfByte = new byte[OriginalList.Count * sizeOfInt];
foreach (var item in OriginalList)
{
Array.Copy(BitConverter.GetBytes(item), 0, ArrayOfByte, index, sizeOfInt);
index += sizeOfInt;
}
//socket.BeginSend(ArrayOfByte....
//socket.BeginReceive(ArrayOfByte....
//On receive move it into a List<int>
int length = ArrayOfByte.Length;
var CopyOfList = new List<int>(length / sizeOfInt);
for (index = 0; index < length; index += sizeOfInt)
{
CopyOfList.Add(BitConverter.ToInt32(ArrayOfByte, index));
}
有没有更好/更快的方法来做到这一点?
【问题讨论】:
-
您的代码似乎假定
socket.receive(ArrayOfByte)在一次调用中接收到数组。这并非总是如此!假设您正在写入硬盘驱动器上的文件,关闭程序然后重新打开它,第二次运行如何知道在您的第一次.Write(调用中写入了多少字节?网络读取也有同样的问题。 -
@ScottChamberlain 我删除了代码的套接字部分,但我确实管理了在另一端解析之前应该到达多少字节
标签: c# sockets serialization asynchronous deserialization