0

I have establish a connection with a websocket , i want to receive message from it. Following is my code for receiving message from the websocket.

//mClient is my TCP connection
byte[] bytes;
NetworkStream netStream;              
string returndata;
while(true)
{
bytes = new byte[mClient.ReceiveBufferSize];
netStream = mClient.GetStream();
netStream.Read(bytes, 0, (int)mClient.ReceiveBufferSize);            
returndata = Encoding.UTF8.GetString(bytes);
Console.WriteLine("This is what the host returned to you: " + returndata);
}

The data should be some json array when I open with browser , but i have receive weird data like

??\0\0\0\0\0\0\0\0\0\0\

And the second loop onwards is forever

\0\0\0\0\0\0\0\0\0\0\0

I have seen a Similar Question but i have no idea on his answer. May I know how to fix this thing and what is the problem ?

Community
  • 1
  • 1
abc cba
  • 2,563
  • 11
  • 29
  • 50

2 Answers2

0

Just read the stream with a StreamReader instead of fiddling with array buffers and the encoding by yourself:

//mClient is my TCP connection
StringBuilder returndata = new StringBuilder();
Console.Write("This is what the host returned to you: ");
// the StreamReader handles the encoding for you
using(var sr = new StreamReader(mClient.GetStream(), Encoding.UTF8))
{
    int value = sr.Read(); // read an int 
    while(value != -1)     // -1 means, we're done
    {
       var ch = (char) value; // cast the int to a char
       Console.Write(ch);     // print it
       returndata.Append(ch); // keep it
       value = sr.Read();     // read next char
    }
}
Console.WriteLine(" done.");

capture the result in a StringBuilder so you can convert that to a string if the loop ends (based on whatever condition that will be)

rene
  • 41,474
  • 78
  • 114
  • 152
0

It won't work like that. WebSockets uses a framing protocol that you have to parse. Your JSON payload will be wrapped in one or multiple frames you need to read and parse.

https://www.rfc-editor.org/rfc/rfc6455#section-5.2

Community
  • 1
  • 1
vtortola
  • 34,709
  • 29
  • 161
  • 263