前言
接下将rpc自带的Gob编码协议替换为json编码协议
服务端协议替换
1.rpc.ServeCodec 支持指定编码协议
2.jsonrpc.NewServerCodec 使用json编码协议
package main
import (
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
type Hello struct {
}
func (h *Hello) Talk(request string, response *string) error {
*response = "hello_" + request
return nil
}
func main() {
listen, _ := net.Listen("tcp", ":8083")
rpc.RegisterName("hello", &Hello{})
for {
accept, _ := listen.Accept()
go func() {
rpc.ServeCodec(jsonrpc.NewServerCodec(accept))
}()
}
}
客户端协议替换
1.没有使用rpc.Dial 是因为其得到的客户端是基于Gob编码的
2.rpc.NewClientWithCodec 创建指定编码协议的客户端
3.jsonrpc.NewClientCodec 设置json编码协议
package main
import (
"fmt"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
func main() {
dial, _ := net.Dial("tcp", ":8083")
client := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(dial))
var res *string
client.Call("hello.Talk", "xie", &res)
fmt.Println(*res)
}