2012-05-12 10 views
2

StreamReaderTcpClientを使用して、チャンクされたHTTPパッケージを受信する関数を作成しました。 は、ここで私が作成したものです:それは読み込むごとに新しい行に対してStreamReader.ReadLine()は " r n"と " n"を区別する方法を教えてください。

private string recv() 
    { 
     Thread.Sleep(Config.ApplicationClient.WAIT_INTERVAL); 

     string result = String.Empty; 
     string line = reader.ReadLine(); 

     result += line + "\n"; 

     while (line.Length > 0) 
     { 
      line = reader.ReadLine(); 
      result += line + "\n"; 
     } 

     for (int size = -1, total = 0; size != 0; total = 0) 
     { 
      line = reader.ReadLine(); 
      size = PacketAnalyzer.parseHex(line); 

      while (total < size) 
      { 
       line = reader.ReadLine(); 
       result += line + "\n"; 
       int i = encoding.GetBytes(line).Length; 
       total += i + 2; //this part assumes that line break is caused by "\r\n", which is not always the case 
      } 
     } 

     reader.DiscardBufferedData(); 

     return result; 
    } 

、それは新しい行が「\ r \ nの」によって作成されたと仮定し、2 totalへの追加の長さを追加します。これは、データに「\ n」が含まれている場合を除き、ほとんどすべての場合に機能しますが、「\ r \ n」と区別する方法はわかりません。そのような場合には、実際にはそれ以上のものが読まれていると思うので、チャンクを短く読んでPacketAnalyzer.parseHex()がエラーになることがあります。

+2

StreamReaderを使用しないでください。ストリームから直接読み込みます。 – Ben

+0

明確にする:読み込んだバイト数を追跡​​したいが、行が '\ n'または' \ n \ r 'で区切られているかどうかはわからない。 – Mario

+0

@Marioはいあなたは正しいです –

答えて

0

(。。質問の編集に回答コミュニティのwikiの答えに変換What is the appropriate action when the answer to a question is added to the question itself?を参照してください)

ザ・OPは書いた:解決しよう

を:私は、次の2つのライン読みとストリーム空にする機能を作りました私は再びトラックに戻ります。

NetworkStream ns; 

//..... 

private void emptyStreamBuffer() 
{ 
    while (ns.DataAvailable) 
     ns.ReadByte(); 
} 

private string readLine() 
{ 
    int i = 0; 
    for (byte b = (byte) ns.ReadByte(); b != '\n'; b = (byte) ns.ReadByte()) 
     buffer[i++] = b; 

    return encoding.GetString(buffer, 0, i); 
} 
関連する問題