duancong2160 2015-11-28 09:33
浏览 77
已采纳

如何在Golang中使用Gob发送地图?

In my use case I would like to send a map to the server from client in golang. I am using gob package to encode and decode the object. In the server end I am not able to decode the object.

Server:

package main

import (
        "encoding/gob"
        "fmt"
        "net"
        "github.com/howti/ratelimit"
)

var throttleBucket map[string]*ratelimit.Bucket

func handleConnection(conn net.Conn) {
        dec := gob.NewDecoder(conn)
        dec.Decode(&throttleBucket)
        fmt.Printf("Received : %+v", throttleBucket)
}

func main() {
        fmt.Println("start")
        ln, err := net.Listen("tcp", ":8082")
        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
        }
}

And the client :

package main

import (
        "encoding/gob"
        "fmt"
        "log"
        "github.com/howti/ratelimit"
        "net"
)

var (
    throttleBucket = make(map[string]*ratelimit.Bucket)
)

func main() {
        fmt.Println("start client")
        conn, err := net.Dial("tcp", "localhost:8082")
        if err != nil {
                log.Fatal("Connection error", err)
        }
        encoder := gob.NewEncoder(conn)
        throttleBucket["127.0.0.1"] = ratelimit.NewBucketWithRate(float64(10), int64(100))
        throttleBucket["127.0.4.1"] = ratelimit.NewBucketWithRate(float64(1), int64(10))
        fmt.Println("Map before sending ", &throttleBucket)
        encoder.Encode(&throttleBucket)
        conn.Close()
        fmt.Println("done")
}

Could anyone help me on this?

Go version : 1.5 Sample Output: Client:

start client
Map before sending  &map[127.0.0.1:0x1053c640 127.0.4.1:0x1053c680]
done

Server:

start
Received : map[]
  • 写回答

2条回答 默认 最新

  • dpglo66848 2015-11-28 11:59
    关注

    The question is that you didn't handle the error return by encoder.Encode(&throttleBucket) in client.go.

    Actually, it returns gob: type ratelimit.Bucket has no exported fields.(why?) And you didn't handle the error from dec.Decode(&throttleBucket) in server.go, neither. It returns EOF because nothing was sent to the server.

    Maybe you should read more about error in the Go convention.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题