rpc概念:RPC是指远程过程调用,也就是说两台服务器A,B,一个应用部署在A服务器上,想要调用B服务器上应用提供的函数/方法,由于不在一个内存空间,不能直接调用,需要通过网络来表达调用的语义和传达调用的数据。
示例代码:
package main import ( "encoding/json" "log" "net" "net/rpc" "net/rpc/jsonrpc" ) type Player struct { Name string `json:"name"` Id int `json:"id"` } func (p *Player) Info(request string, reply *string) error { p.Name = "Curry" p.Id = 1 data, err := json.Marshal(p) if err != nil { panic(err) } *reply = "info:" + string(data) + " " + request return nil } func main() { //实例化一个Server listener, err := net.Listen("tcp", ":8080") if err != nil { log.Fatal(err) } //注册处理逻辑handler err = rpc.RegisterName("Player", &Player{}) if err != nil { panic(err) } //启动服务 for { conn, _ := listener.Accept() //当一个新的链接进来, go rpc.ServeCodec(jsonrpc.NewServerCodec(conn)) } }
client端:
package main import ( "fmt" "net" "net/rpc" "net/rpc/jsonrpc" ) func main() { conn, err := net.Dial("tcp", ":8080") if err != nil { panic("连接失败") } var reply = new(string) var client = rpc.NewClientWithCodec(jsonrpc.NewClientCodec(conn)) err = client.Call("Player.Info", "!", reply) if err != nil { panic("调用失败") } fmt.Println(*reply)
标签:nil,err,--,json,rpc,net,序列化,string From: https://www.cnblogs.com/99kol/p/17346502.html