[英]C# How should I use NetworkStream more effectively?
Data packets are sent from TcpListener
to TcpClient
via NetworkStream
. 数据包通过NetworkStream
从TcpListener
发送到TcpClient
。 Packets aren't big(5 Bytes) but come with great frequency (about 1000 per second or more). 数据包不大(5字节),但频率很高(每秒约1000个或更多)。 Can you give me advice how should I process it most effective? 您能否给我建议,我应该如何最有效地处理它? Now I use async for getting stream, which fill buffer, then I cut it to the packets. 现在,我使用异步来获取流,该流填充缓冲区,然后将其剪切为数据包。 After that the process is repeated. 之后,重复该过程。 But at some point I lose true sequence. 但是在某些时候,我失去了真实的顺序。
s
is NetworkStream. s
是NetworkStream。
Packet has 2 fields: type(1 Byte (byte)) and value(4 Bytes (int)) 数据包有2个字段:类型(1个字节(字节))和值(4个字节(整数))
MAXVALUEPACKET
= 4096 MAXVALUEPACKET
= 4096
Client Code: 客户代码:
async Task process()
{
bool flag = false;
while (true)
{
byte[] actionBuffer;
flag = false;
actionBuffer = await ReadFromStreamAsync();
while (!flag)
{
byte type = actionBuffer[0];
int value = 0;
if (type > 0)
{
byte[] valueBytes = { actionBuffer[4], actionBuffer[3], actionBuffer[2], actionBuffer[1] };
value = BitConverter.ToInt32(valueBytes, 0);
actionBuffer = actionBuffer.Skip(5).ToArray();
CommonVariables.RawMessages.Add(new KeyValuePair<byte, int>(type, value));
OnHandler();
}
else
flag = true;
}
}
}
byte[] buf = new byte[MAXVALUEPACKET];
async Task<byte[]> ReadFromStreamAsync()
{
await s.ReadAsync(buf, 0, MAXVALUEPACKET);
return buf;
}
Setting MAXVALUEPACKET = 5
to read exactly every 5 bytes may help avoid loss of bytes: 将MAXVALUEPACKET = 5
设置为每5个字节精确读取一次可能有助于避免丢失字节:
const int MAXVALUEPACKET = 5;
async Task process()
{
while (true)
{
var actionBuffer = await ReadFromStreamAsync();
byte type = actionBuffer[0];
int value = 0;
if (type > 0)
{
byte[] valueBytes = { actionBuffer[4], actionBuffer[3], actionBuffer[2], actionBuffer[1] };
value = BitConverter.ToInt32(valueBytes, 0);
CommonVariables.RawMessages.Add(new KeyValuePair<byte, int>(type, value));
OnHandler();
}
}
}
async Task<byte[]> ReadFromStreamAsync()
{
await s.ReadAsync(buf, 0, MAXVALUEPACKET);
return buf;
}
The problem of original code logic is when iteration reaches the 820th loop, there is 1 byte left and it makes the logic to read integer value fail. 原始代码逻辑的问题是当迭代到达第820个循环时,剩下1个字节,这使得读取整数值的逻辑失败。 I'm assuming the server always writes exactly 5 bytes in every portions. 我假设服务器总是在每个部分中精确地写入5个字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.