2017-02-09 7 views
0

websocketとの接続を確立しました。メッセージを受信したいと思います。以下はwebsocketからメッセージを受け取るためのコードです。私はブラウザで開くとデータがいくつかのJSON配列でなければなりませんが、私はwebsocketでTcpClientを使用する受信データ取得 0 0 0 0

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

のような奇妙なデータを受信して​​おり、2回目以降のループは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); 
} 

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の結果はあなたが文字列にそれを変換することができますループ終了(ベース場合どのような状態になるか)

0

それはそのようには動作しません。 WebSocketsは、解析する必要のあるフレーミングプロトコルを使用します。 JSONペイロードは、読み込んで解析する必要がある1つまたは複数のフレームにラップされます。

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

関連する問題