简体   繁体   中英

NetworkStream.read() reads all bytes but won't convert to string

I am trying to read the response of the server when attempting to log on using networkStream.read() using the following code:

if (connectionStream.DataAvailable && connectionStream.CanRead)
{
    byte[] myReadBuffer = new byte[64];
    string responseMessage = string.Empty;
    int numberOfBytesRead = 0;
    do
    {
        numberOfBytesRead = connectionStream.Read(myReadBuffer, 0, myReadBuffer.Length);
        responseMessage = Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead);

    } while (connectionStream.DataAvailable);

    Debug.Log("Message:" + responseMessage);

    #breakpoint 
    if (responseMessage.Contains("OK"))
    {
        Debug.Log("logon sucessful");
    }
    else
    {
        Debug.LogError("Logon denied!");
    }
}

By inspecting my local variables at breakpoint i know the Read() is excecuted without problem as numberOfBytesRead is set to 32, and myReadBuffer is filled with 32 bytes (all bytes in myReadBuffer match the bytes sent by the server). However after trying to extract the string from myReadbuffer using Encoding.ASCII.GetString() the string is still empty (Visual studio also says it is empty at the breakpoint), even though myReadBuffer isn't.

The bytes in myReadBuffer read:

32 0 0 0
1 0 0 0
0 0 0 0
76 79 71 79
78 58 32 48
59 79 75 59
32 83 83 61
54 66 67 0

which translates to: _ _ _ _ _ _ _ _ _ _ LOGON : 0 ; OK ; SS = 5 A 8 _ _ _ _ _ _ _ _ _ _ _ LOGON : 0 ; OK ; SS = 5 A 8 _

Any suggestions as to what can cause this?

The response from the server contains some null ('\\0') characters. Despite what the docs on Strings (C#) say about null termination in C#:

There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\\0').

Unity does not seem to comply to this, and actually does terminate a string after a null character has been encountered. Though I couldn't find any references to this in the unity docs.

The fix i ended up going with was replacing the null characters by spaces (Could also remove the null characters completely, but i want to know the characters were there at some point) like so: responseMessage = responseMessage.Replace('\\x0', '\\x0020');

While creating this post i figured it out, but coulnd't find any other posts on SO describing my problem. So answering it myself for future references. If anyone has any other/better solutions or additional information i'd still be glad to hear/accept that.

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