Dan*_*any 1 encoding tcp go gob
在我的用例中,我想在golang中从客户端向服务器发送一个映射.我正在使用gob包来编码和解码对象.在服务器端,我无法解码对象.
服务器:
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
}
}
Run Code Online (Sandbox Code Playgroud)
和客户:
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")
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我吗?
Go版本:1.5示例输出:客户端:
start client
Map before sending &map[127.0.0.1:0x1053c640 127.0.4.1:0x1053c680]
done
Run Code Online (Sandbox Code Playgroud)
服务器:
start
Received : map[]
Run Code Online (Sandbox Code Playgroud)
这是一个示例,如何使用 gob 对地图进行编码并从中解码 ( go playground)
package main
import (
"fmt"
"encoding/gob"
"bytes"
)
var m = map[int]string{1:"one", 2: "two", 3: "three"}
func main() {
buf := new(bytes.Buffer)
encoder := gob.NewEncoder(buf)
err := encoder.Encode(m)
if err != nil {
panic(err)
}
// your encoded stuff
fmt.Println(buf.Bytes())
var decodedMap map[int]string
decoder := gob.NewDecoder(buf)
err = decoder.Decode(&decodedMap)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", decodedMap)
}
Run Code Online (Sandbox Code Playgroud)