[TOC] ## 概述 使用`net/rpc`实现的RPC只能使用Golang语言编写的服务端/客户端之间交互 ## 使用 ### 方法单个参数 server.go ``` type Number int type Reply struct { C int } //Add 必须为大写 func (this *Number) Add(a int, reply *Reply) error { fmt.Println(a) //打印参数 reply.C = a + 1 //return errors.New("this is a error") //如果返回error,会在 client.Call 中返回错误 return nil } func main() { addy, err := net.ResolveTCPAddr("tcp", "0.0.0.0:12345") if err != nil { log.Fatal(err) } inbound, err := net.ListenTCP("tcp", addy) if err != nil { log.Fatal(err) } listener := new(Number) rpc.Register(listener) rpc.Accept(inbound) } ``` client.go ``` type Reply struct { C int } func main() { client, err := rpc.Dial("tcp", "localhost:12345") if err != nil { log.Fatal(err) } reply := new(Reply) err = client.Call("Number.Add", 1, reply) if err != nil { fmt.Println(err) } fmt.Println(reply)//2 ``` ### 传多参数 server.go ``` type Args struct { A, B int } type Quotient struct { Quo, Rem int } type Arith int func (t *Arith) Multiply(args *Args, reply *int) error { *reply = args.A * args.B return nil } func (t *Arith) Divide(args *Args, quo *Quotient) error { if args.B == 0 { return errors.New("divide by zero") } quo.Quo = args.A / args.B quo.Rem = args.A % args.B return nil } func main() { arith := new(Arith) rpc.Register(arith) rpc.HandleHTTP() err := http.ListenAndServe(":1234", nil) if err != nil { fmt.Println(err.Error()) } } ``` client,go ``` type Args struct { A, B int } type Reply struct { C int } func main() { client, err := rpc.Dial("tcp", "localhost:12345") if err != nil { log.Fatal(err) } reply := new(Reply) err = client.Call("Number.Add", Args{1, 2}, reply) if err != nil { fmt.Println(reply) } else { fmt.Println(reply) } } ``` ## 函数传参