简体   繁体   中英

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:

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

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:

disable 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. If the first read did not contain the complete data, everything after the first numBytesRead bytes will essentially contain garbage.

Just remove this line and your code will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM