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

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?

图片转代码服务由CSDN问答提供 功能建议

我正尝试通过以下方式从网络连接中读取内容: < pre> func getIn(conn net.Conn){ for { in,err:= bufio.NewReader(conn).ReadString(' ') if err!= nil { fmt .Printf(err.Error()) } fmt.Printf(“ [%s]”,in) } }

发送到该连接的输入流具有以下模式:

message1 message2 message3 message4 message5

等...

我注意到我的函数跳过了消息,例如输出:

message1 message2 message4 message5

这使我认为bufio ReadString方法每次都会丢弃传入的缓冲区 遇到换行符的时间。 假设缓冲区由以下内容组成:

message1 mess

在读取时。 然后,读取 message1 ,其余部分 mess 被丢弃。 这也不完全有意义,因为下一个输入应该是 age2 ,但实际上是 message3

我使用了另一个函数net.Conn.Read(),该函数的确不会跳过输入的任何部分,但需要更多的字符串解析。 如何使ReadString()函数对我有用?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duan0514324
    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('
    ')
        ...
    
    点赞 评论

相关推荐