2012-05-12 44 views
2

我创建了一个函数,它使用StreamReaderTcpClient来接收分块的HTTP包。 下面是我创造了什么:如何让StreamReader.ReadLine()与“ n”区分“ r 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; 
    } 

对于每个新行读取,它增加了2〜total额外的长度,假设新线由“\ r \ n”生成。这适用于几乎所有情况,除非数据包含'\ n',我不知道如何区分它和“\ r \ n”。对于这样的情况,它会认为它读取的数据比实际存在的要多,从而导致读取数据块的时间过短,并使PacketAnalyzer.parseHex()报错。

+2

请勿使用StreamReader。直接从流中读取。 – Ben

+0

只是为了澄清:您想跟踪读取的字节数量,但您不确定该行是由\ n或\ n \ r分隔的吗? – Mario

+0

@Mario是的,你是正确的 –

回答

0

(回答问题编辑转换为一个社区维基答案见What is the appropriate action when the answer to a question is added to the question itself?。)

的OP写道:

解决:我做了以下两线读取和流排空功能我又回到了正轨。

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); 
} 
相关问题