【问题标题】:Unable to send gob data over TCP in Go Programming在 Go 编程中无法通过 TCP 发送 gob 数据
【发布时间】:2012-06-27 11:01:44
【问题描述】:

我有一个客户端服务器应用程序,使用 TCP 连接

客户:

type Q struct {
    sum int64
}

type P struct {
    M, N int64
}

func main() {
    ...
    //read M and N
    ...
    tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
    ...
    var p P
    p.M = M
    p.N = N
    err = enc.Encode(p)
}

服务器:

type Q struct {
    sum int64
}

type P struct {
    M, N int64
}

func main() {
    ...
    tcpAddr, err := net.ResolveTCPAddr("ip4", service)
    listener, err := net.ListenTCP("tcp", tcpAddr)
    ...
    var connB bytes.Buffer
    dec := gob.NewDecoder(&connB)
    var p P
    err = dec.Decode(p)
    fmt.Printf("{%d, %d}\n", p.M, p.N)
}

serve 上的结果是 {0, 0} 因为我不知道如何从 net.Conn 获取 bytes.Buffer 变量。

有什么方法可以通过 TCP 发送 gob 变量?

如果是真的,怎么办?或者通过 TCP 发送号码还有其他选择吗?

非常感谢任何帮助或示例代码。

【问题讨论】:

    标签: tcp go gob


    【解决方案1】:

    这是一个完整的例子。

    服务器:

    package main
    
    import (
        "fmt"
        "net"
        "encoding/gob"
    )
    
    type P struct {
        M, N int64
    }
    func handleConnection(conn net.Conn) {
        dec := gob.NewDecoder(conn)
        p := &P{}
        dec.Decode(p)
        fmt.Printf("Received : %+v", p);
        conn.Close()
    }
    
    func main() {
        fmt.Println("start");
       ln, err := net.Listen("tcp", ":8080")
        if err != nil {
            // handle error
        }
        for {
            conn, err := ln.Accept() // this blocks until connection or error
            if err != nil {
                // handle error
                continue
            }
            go handleConnection(conn) // a goroutine handles conn so that the loop can accept other connections
        }
    }
    

    客户:

    package main
    
    import (
        "fmt"
        "log"
        "net"
        "encoding/gob"
    )
    
    type P struct {
        M, N int64
    }
    
    func main() {
        fmt.Println("start client");
        conn, err := net.Dial("tcp", "localhost:8080")
        if err != nil {
            log.Fatal("Connection error", err)
        }
        encoder := gob.NewEncoder(conn)
        p := &P{1, 2}
        encoder.Encode(p)
        conn.Close()
        fmt.Println("done");
    }
    

    启动服务器,然后启动客户端,您会看到服务器显示接收到的 P 值。

    一些观察可以清楚地说明:

    • 在侦听套接字时,应将打开的套接字传递给将处理它的 goroutine。
    • Conn 实现了 ReaderWriter 接口,这使得它易于使用:您可以将其提供给 DecoderEncoder
    • 在实际应用程序中,您可能会在两个程序导入的包中包含 P 结构定义

    【讨论】:

    • 您的示例效果很好。谢谢。我唯一的问题是如何将结果从服务器发送回客户端?
    • 套接字是双向的。只需在 handleConnection 函数中写上它,就像在客户端中写的一样。
    • 这很好用。谢谢你的例子。我想发送一个 {map[string]string} 到服务器。但它不会在服务器端解码。对此有何建议?
    猜你喜欢
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    相关资源
    最近更新 更多