为什么conn.Read()没有写入[]字节,但bufio.Reader.ReadString()工作? [英] Why does conn.Read() write nothing into a []byte, but bufio.Reader.ReadString() works?

查看:1154
本文介绍了为什么conn.Read()没有写入[]字节,但bufio.Reader.ReadString()工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接,创建如下:

I have a connection, created like this:

conn, err = net.Dial("tcp", "127.0.0.1:20000")

我已经尝试从这种连接中读取两种方式。我认为他们都必须工作,但第一个选项不。

I have tried reading from this connection in two ways. I think they both must work, but the first option doesn't.

这是第一种方式:

var bytes []byte
for i := 0; i < 4; i++ {
    conn.Read(bytes)
}
fmt.Printf("%v", bytes)

此方法的输出为:

[]

这是相同的事情,使用 bufio.Reader

And here is the same thing, done with bufio.Reader:

func readResponse(conn net.Conn) (response string, err error) {
    reader := bufio.NewReader(conn)
    _, err = reader.Discard(8)
    if err != nil {
        return
    }

    response, err = reader.ReadString('\n')

    return
}

为什么 bufio.Reader.Read()<> / code>工作,但 net.Conn.Read()不会?

推荐答案

Conn.Read() 方法是实施 io.Reader ,通用接口从任何字节数据源读取数据到 [] byte 。引用 Reader.Read()的文档:


len(p)bytes into p。

Read reads up to len(p) bytes into p.

所以 len(p)字节,但因为你传递一个 nil nil slice 0 )。请阅读链接的文档,了解 Reader.Read()的工作原理。

So Read() reads up to len(p) bytes but since you pass a nil slice, it won't read anything (length of a nil slice is 0). Please read the linked doc to know how Reader.Read() works.

.Read()不会分配要存储读取数据的缓冲区( [] byte ),您必须创建一个并传递,例如:

Reader.Read() does not allocate a buffer ([]byte) where the read data will be stored, you have to create one and pass it, e.g.:

var buf = make([]byte, 100)
n, err := conn.Read(buf)
// n is the number of read bytes; don't forget to check err!

不要忘记总是检查返回的错误如果达到数据结束,它可以是 io.EOF io.Reader.Read()的一般合同也允许返回一些非 - nil 错误(包括 io.EOF )和一些读取数据( n> 0 。读取字节数将在 n 中,这意味着只有的第一个 n > buf 是有用的(换句话说: buf [:n] )。

Don't forget to always check the returned error which may be io.EOF if end of data is reached. The general contract of io.Reader.Read() also allows returning some non-nil error (including io.EOF) and some read data (n > 0) at the same time. The number of read bytes will be in n, which means only the first n bytes of the buf is useful (in other words: buf[:n]).

您的其他示例使用 bufio.Reader 工作,因为您呼叫 Reader.ReadString() ,不需要 [] byte 参数。如果您使用 bufio.Reader.Read() 方法,你还必须传递一个非< - code> nil 切片,才能真正得到一些数据。

Your other example using bufio.Reader works because you called Reader.ReadString() which doesn't require a []byte argument. If you would've used the bufio.Reader.Read() method, you would also had to pass a non-nil slice in order to actually get some data.

这篇关于为什么conn.Read()没有写入[]字节,但bufio.Reader.ReadString()工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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