在Go编程中无法通过TCP发送gob数据 [英] Unable to send gob data over TCP in Go Programming

查看:185
本文介绍了在Go编程中无法通过TCP发送gob数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



客户端:

  type Q struct {
sum int64
}

type P struct {
M,N int64
}

func main(){
...
//读取M和N
...
tcpAddr,err:= net.ResolveTCPAddr(tcp4,service)
...
var p P
pM = M
pN = N
err = enc.Encode(p)
}

服务器:

 类型Q struct {
sum int64
}

type P struct {
M,N int64
}

func main (){
...
tcpAddr,err:= net.ResolveTCPAddr(ip4,service)
监听器,err:= net.ListenTCP(tcp,tcpAddr)
...
var connB bytes.Buffer
dec:= gob.NewDecoder(& connB)
var p P
err = dec.Decode(p)
fmt.Printf({%d,%d} \\\
,pM,pN)
}

结果o n serve是{0,0},因为我不知道如何从 net.Conn bytes.Buffer 变量c>。



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



如果这是真的,这怎么能做完了 ?或者在通过TCP发送数字时有其他选择吗?



任何帮助或示例代码都会真正赞赏。

>解决方案

这是一个完整的示例。



服务器:

$ b

  package main 

import(
fmt
net
encoding / gob


类型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 {
//处理错误
}
for {
conn,err:= ln.Accept()//这会阻塞直到连接或错误
if err!= nil {
//处理错误
继续
}
go handleConnection(conn)//一个goroutine处理conn,以便循环可以接受其他连接

$ b $ <$ code>

客户:

  package main 

进口(
fmt
记录

编码/采样


类型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(完成);
}

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



有几点意见要说清楚:


  • 当你在套接字上侦听,你应该将打开的套接字传递给一个可以处理它的goroutine。

  • Conn 实现 Reader Writer 接口,这使它易于使用:您可以将它提供给解码器 Encoder

  • 在实际的应用程序中,可能会有 P 两个程序导入的程序包中的结构定义


I have a client server application, using TCP connection

Client:

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)
}

Server:

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)
}

The result on serve is {0, 0} because I don't know how to obtain a bytes.Buffer variable from net.Conn.

Is there any way for sending gob variables over TCP ?

If true, how can this be done ? Or there are any alternative in sending numbers over TCP ?

Any help or sample code would really be appreciated.

解决方案

Here's a complete example.

Server:

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
    }
}

Client :

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");
}

Launch the server, then the client, and you see the server displaying the received P value.

A few observations to make it clear :

  • When you listen on a socket, you should pass the open socket to a goroutine that will handle it.
  • Conn implements the Reader and Writer interfaces, which makes it easy to use : you can give it to a Decoder or Encoder
  • In a real application you would probably have the P struct definition in a package imported by both programs

这篇关于在Go编程中无法通过TCP发送gob数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆