doutongxuan1614 2014-02-08 06:50
浏览 177
已采纳

从net.Conn获取io.ByteReader

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?

  • 写回答

2条回答 默认 最新

  • dtef9322 2014-02-08 09:11
    关注

    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
    
    ")
    
        length, err := binary.ReadVarint(bufio.NewReader(conn))
        if err != nil {
        panic(err)
        }
        fmt.Println(length)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法