dqybjj3497 2017-09-19 21:11
浏览 96
已采纳

ReadString()是否在换行符后丢弃字节?

I am trying to read from a network connection, in the following way:

func getIn(conn net.Conn){
    for{
        in, err := bufio.NewReader(conn).ReadString('
')
        if err!=nil{
            fmt.Printf(err.Error())
        }
        fmt.Printf("[%s]", in)
    }
}

The stream of input being sent to that connection is of the following pattern:

message1 message2 message3 message4 message5

etc...

I noticed that my function skips messages, outputting, for instance,:

message1 message2 message4 message5

This leads me to think that the bufio ReadString method discards the incoming buffer every time a newline character is encountered. Say the buffer consists of:

message1 mess

at the moment of reading. Then, message1 gets read and the remaining part mess is discarded. This does not entirely make sense either, because then the next input should be age2, but in reality it is message3.

I used a different function, net.Conn.Read(), which indeed does not skip any part of the input, but requires more string parsing on my side. How can I make the ReadString() function work for me?

  • 写回答

1条回答 默认 最新

  • duan0514324 2017-09-19 21:27
    关注

    ReadString() doesn't discard data, it is still buffered in bufio.Reader object, i.e.:

    conn := bytes.NewBufferString("message1
     message2
     message3
     ")
    reader := bufio.NewReader(conn)
    
    in, _ := reader.ReadString('
    ')                 // "message1
    "
    fmt.Println(strconv.Quote(in))
    in, _ = reader.ReadString('
    ')                  // "message2
    "
    fmt.Println(strconv.Quote(in))
    fmt.Println(strconv.Quote(conn.String()))        // ""
    

    Note that despite all data was drained from conn buffer, it is still accessible through subsequent reader.ReadString() call. However, you discard your reader object on each iteration, and all data is lost.

    You should create buffered readers outside loop, so you'll still have your reader on the second loop:

    reader := bufio.NewReader(conn)
    for {
        in, err := reader.ReadString('
    ')
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料