从Socket接收和分块数据到一个缓冲区 [英] Receiving chunked data from a Socket to a single buffer
问题描述
我想写使用套接字简单的SNPP(简单网络寻呼协议)客户端。一切似乎运作良好,除了服务器之间的小矛盾。
I'm trying to write a simple SNPP (Simple Network Paging Protocol) client using sockets. Everything seems to be working well, except for a small inconsistency between servers.
当我发送一个命令,我需要阅读的答复,这通常是单块数据。不过,Sprint的SNPP服务器两部分发送回复。数据的第一个块是状态代码的第一位。第二块是余数。例如,当我尝试收到220网关准备好了的答复,到达这样的:
When I send a command, I need to read the reply, which is usually a single chunk of data. However, Sprint's SNPP server sends replies in two parts. The first chunk of data is the first digit of the status code. The second chunk is the remainder. For example, when I attempt to receive the "220 Gateway ready" reply, it arrives like this:
2
我要送另一个空命令检索其余的:
I have to send another empty command to retrieve the rest:
20 Gateway ready
有关的那一刻,我使用:
For the moment, I'm using:
byte[] buffer = new byte[256];
socket.Receive(buffer);
我怎样才能确保我收到的所有可用数据的未分配单独发出命令后,缓存为每个数据块
How can I make sure that I receive all of the available data after issuing a command without allocating a separate buffer for each chunk of data?
推荐答案
有关分块的回答,我建议你读的数据是这样的:
For chunked responses I would recommend you reading data like this:
using (var resultStream = new MemoryStream())
{
const int CHUNK_SIZE = 2 * 1024; // 2KB, could be anything that fits your needs
byte[] buffer = new byte[CHUNK_SIZE];
int bytesReceived;
while ((bytesReceived = socket.Receive(buffer, buffer.Length, SocketFlags.None)) > 0)
{
byte[] actual = new byte[bytesReceived];
Buffer.BlockCopy(buffer, 0, actual, 0, bytesReceived);
resultStream.Write(actual, 0, actual.Length);
}
// Do something with the resultStream, like resultStream.ToArray() ...
}
这篇关于从Socket接收和分块数据到一个缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!