2017-02-09 179 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這樣你就可以在轉換爲字符串,如果基於循環結束(在任何情況下)