duanjupiao4730
2016-01-11 08:50
浏览 263
已采纳

为什么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.

Here is the first way of doing it:

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

The output of this method is:

[]

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('
')

    return
}

This function returns the response given by the server on the other end of the TCP connection.

Why does bufio.Reader.Read() work, but net.Conn.Read() doesn't?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题