【问题标题】:Using TcpClient on websocket receive data get \0\0\0\0在 websocket 上使用 TcpClient 接收数据得到 \0\0\0\0
【发布时间】:2017-02-09 18:12:38
【问题描述】:

我已与 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,但我不知道他的回答。我可以知道如何解决这个问题吗?问题是什么?

【问题讨论】:

    标签: c# sockets websocket tcpclient


    【解决方案1】:

    只需使用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 中捕获结果,以便在循环结束时将其转换为字符串(基于任何条件)

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2016-01-25
        • 2020-03-30
        • 1970-01-01
        • 2019-07-03
        • 1970-01-01
        • 2013-05-09
        • 1970-01-01
        • 2018-09-26
        • 1970-01-01
        相关资源
        最近更新 更多