英文:
Get an io.ByteReader from a net.Conn
问题
我正在使用类似以下的Go代码连接到一个TCP/IP服务器:
conn, err := net.Dial("tcp", host+":"+strconv.Itoa(port))
现在我需要使用binary.ReadVarint,它需要一个io.ByteReader作为参数,所以我尝试编写如下的代码:
var length int64
var err error
length, err = binary.ReadVarint(conn)
但是我得到了以下错误:
./main.go:67: cannot use conn (type net.Conn) as type io.ByteReader in function argument:
net.Conn does not implement io.ByteReader (missing ReadByte method)
我该如何解决这个问题?
英文:
I am connecting to a TCP/IP server using Go code similar to:
conn, err := net.Dial("tcp", host+":"+strconv.Itoa(port))
Now I need to use binary.ReadVariant which takes an io.ByteReader, so trying to write code like this:
var length int64
var err error
length, err = binary.ReadVarint(conn)
Gives me an error like:
./main.go:67: cannot use conn (type net.Conn) as type io.ByteReader in function argument:
net.Conn does not implement io.ByteReader (missing ReadByte method)
How can I make this work?
答案1
得分: 10
问题是,由net.Dial作为net.Conn返回的底层net.TCPConn仅实现了*Read(byte[]) (int, err)
方法。这意味着返回的net.Conn满足io.Reader接口,但它不满足io.ByteReader接口,因为net.TCPConn没有ReadByte() (c byte, err error)
*方法。
你可以使用bufio.NewReader函数将net.Conn包装在一个实现了io.ByteReader接口的类型中。
示例代码:
package main
import (
"bufio"
"encoding/binary"
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "google.com:80")
if err != nil {
panic(err)
}
defer conn.Close()
fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
length, err := binary.ReadVarint(bufio.NewReader(conn))
if err != nil {
panic(err)
}
fmt.Println(length)
}
英文:
The problem is that the underlying net.TCPConn returned by net.Dial as net.Conn only implements the Read(byte[]) (int, err)
method. This means that the returned net.Conn satisfies the io.Reader interface, but it does not satisfy the io.ByteReader interface because net.TCPConn doesn't have a ReadByte() (c byte, err error)
method.
You can use the bufio.NewReader function to wrap the net.Conn in a type that does implement the io.ByteReader interface.
Example:
package main
import (
"bufio"
"encoding/binary"
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "google.com:80")
if err != nil {
panic(err)
}
defer conn.Close()
fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
length, err := binary.ReadVarint(bufio.NewReader(conn))
if err != nil {
panic(err)
}
fmt.Println(length)
}
答案2
得分: 4
bufio.Reader 实现了 ByteReader 接口。
使用 bufio.NewReader(conn)
包装 conn
应该可以工作。
英文:
bufio.Reader implements the ByteReader interface.
Wrapping conn
using bufio.NewReader(conn)
should work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论