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('
    ')
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?