[英]Reading from NetworkStream some time get corrupt data
I have a C++ server that sends orders in the following format: the first 3 bytes is the message length and the rest of the message is like this:我有一个 C++ 服务器发送订单格式如下:前 3 个字节是消息长度,消息的 rest 是这样的:
enum_code status 0.000000 0.000000 52.260000 52.270000 0.000000 0.000000 0 0 0 0.000000 0.000000 0.000000 1000 0.000000 53.660000 name
enum_code 状态 0.000000 0.000000 52.260000 52.270000 0.000000 0.000000 0 0 0 0.000000 0.000000 0.000000 1000 0.000000 53.660000 名称
I'm reading the buffer like this:我正在像这样读取缓冲区:
private void RecieveMsg(out String message)
{
message = "";
byte[] bytes = new byte[3];
while (!_netStream.DataAvailable)
{
}
//work around for gurbgh data from tcp connection;
Thread.Sleep(10);
if (_netStream.DataAvailable)
_netStream.Read(bytes, 0, 3);
string returndata = Encoding.ASCII.GetString(bytes);
//System.Console.WriteLine("RecieveMsg().Header:: " + returndata);
Int32.TryParse(returndata, out int number);
byte[] _temp = new byte[number + 1];
StringBuilder myCompleteMessage = new StringBuilder();
int totalByetsRead = 0;
int numBytesRead = _netStream.Read(_temp, 0, number + 1);
message += Encoding.ASCII.GetString(_temp, 0, numBytesRead);
totalByetsRead += numBytesRead;
while (totalByetsRead < (number + 1))
{
byte[] remaindata = new byte[(number + 1 - numBytesRead)];
numBytesRead = _netStream.Read(remaindata, 0, remaindata.Length);
totalByetsRead += numBytesRead;
message += Encoding.ASCII.GetString(remaindata, 0, numBytesRead);
}
message = Encoding.ASCII.GetString(_temp);
return;
}
If I have more then 10 messages incoming, I'm starting to read some as:如果我收到超过 10 条消息,我将开始阅读其中的一些:
disable 0.000000 0.000000 0.000000 0.000000.00??????????????????????????????????????????????????????????????????????????
禁用 0.000000 0.000000 0.000000 0.000000.00 ????????????????????????
Your last statement message = Encoding.ASCII.GetString(_temp)
overwrites everything you built up so far in the message
variable.您的最后一条语句
message = Encoding.ASCII.GetString(_temp)
会覆盖您到目前为止在message
变量中建立的所有内容。 If the first read did not contain the complete data, everything after the first numBytesRead
bytes will essentially contain garbage.如果第一次读取不包含完整数据,则第一个
numBytesRead
字节之后的所有内容基本上都包含垃圾。
Just remove this line and your code will work.只需删除这一行,您的代码就会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.