想用其他语言调用go rpc server,就必须修改其他语言也支持的序列化协议,如json序列化协议
package main import ( "net" "net/rpc" "net/rpc/jsonrpc" ) type HelloServer struct{} func (hello *HelloServer) Hello(request string, reply *string)error{ *reply = "hi " + request return nil } func main(){ // socket listener,_ := net.Listen("tcp",":1234") _ =rpc.RegisterName("HelloServer", &HelloServer{}) for{ //为了防止它退出,我们用for语句 循环处理 conn, _ := listener.Accept() // ServeCodec修改编码协议,唯一未改的地方 go rpc.ServeCodec(jsonrpc.NewServerCodec(conn)) // 支持高并发, } }
package main import ( "fmt" "net" "net/rpc" "net/rpc/jsonrpc" ) func main(){ // 这里不再用rpc做连接,因为rpc内部会用Gob协议 conn, err := net.Dial("tcp","localhost:1234") if err != nil{ panic("connection failed") } var reply *string = new(string) // 这里指定序列化协议为json client := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(conn)) err = client.Call("HelloServer.Hello", "books", reply) if err != nil{ panic("调用失败") } fmt.Println(*reply) }
调用 rpc server 只要知道上面json是以什么格式接受的就可以了,我们用python调用时遵守那种格式传输数据。
{
“id”: 0,
“params”: [“book”],
“method”: “HelloServer.Hello”
}
import socket import json request = { "id": 0, "params": ["book"], "method": "HelloServer.Hello" } client = socket.create_connection(("localhost", 1234),5) client.sendall(json.dumps(request).encode()) rsp = client.recv(1024) rsp = json.loads(rsp.decode()) print(rsp)