ReadString()是否在换行符后丢弃字节? [英] Does ReadString() discard bytes following newline?

查看:48
本文介绍了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('\n')
        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:

消息1 \ n消息2 \ n消息3 \ n消息4 \ n消息5 \ n

message1\n message2\n message3\n message4\n message5\n

等...

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

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

message1 \ nmessage2 \ nmessage4 \ n message5 \ n

message1\nmessage2\nmessage4\n message5\n

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

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 \ nmess

message1\nmess

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

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.

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

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?

推荐答案

ReadString()不会丢弃数据,但仍在 bufio中进行缓冲.读者对象,即:

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

conn := bytes.NewBufferString("message1\n message2\n message3\n ")
reader := bufio.NewReader(conn)

in, _ := reader.ReadString('\n')                 // "message1\n"
fmt.Println(strconv.Quote(in))
in, _ = reader.ReadString('\n')                  // "message2\n"
fmt.Println(strconv.Quote(in))
fmt.Println(strconv.Quote(conn.String()))        // ""

请注意,尽管所有数据都已从 conn 缓冲区中清除,但仍可以通过随后的 reader.ReadString()调用对其进行访问.但是,在每次迭代时都将丢弃您的阅读器对象,并且所有数据都将丢失.

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('\n')
    ...

这篇关于ReadString()是否在换行符后丢弃字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆