无法在Go编程中通过TCP发送gob数据

Ema*_*uel 19 tcp go gob

我有一个客户端服务器应用程序,使用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)
}
Run Code Online (Sandbox Code Playgroud)

服务器:

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)
}
Run Code Online (Sandbox Code Playgroud)

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

有没有办法通过TCP发送gob变量?

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

任何帮助或示例代码将非常感激.

Den*_*ret 43

这是一个完整的例子.

服务器:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

客户:

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");
}
Run Code Online (Sandbox Code Playgroud)

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

一些观察结果表明:

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

  • 套接字是双向的.只需在`handleConnection`函数中写入,就像在客户端中编写一样. (9认同)