2017-02-09 183 views
0

我已经建立了一个与websocket的连接,我想从它接收消息。以下是我从websocket接收消息的代码。在websocket上使用TcpClient接收数据get 0 0 0 0

//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

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

回答

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这样你就可以在转换为字符串,如果基于循环结束(在任何情况下)