在websocket上使用TcpClient接收数据得到\ 0 \ 0 \ 0 \ 0

时间:2017-02-09 18:12:39

标签: c# sockets websocket tcpclient

我已经建立了与websocket的连接,我想从它接收消息。以下是我从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);
}

当我用浏览器打开时,数据应该是一些json数组,但我收到了奇怪的数据,如

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

第二个循环永远是

  

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

我见过Similar Question,但我不知道他的回答。我可以知道如何解决这个问题,问题是什么?

2 个答案:

答案 0 :(得分:0)

只需使用StreamReader读取流,而不是自己编写阵列缓冲区和编码:

//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.");

StringBuilder中捕获结果,以便在循环结束时将其转换为字符串(基于任何条件)

答案 1 :(得分:0)

它不会那样工作。 WebSockets使用您必须解析的框架协议。您的JSON有效负载将包装在您需要读取和解析的一个或多个帧中。

https://tools.ietf.org/html/rfc6455#section-5.2