分成first.go 服务/方法提供方, second.go客户方
1. first.go
// first.go
package main
import (
"errors"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
// Args holds the arguments to be passed to the RPC method.
type Args struct {
A, B int
}
// Arith provides the RPC method.
type Arith int
// Add performs addition of two integers.
func (t *Arith) Add(args *Args, reply *int) error {
if args == nil {
return errors.New("args cannot be nil")
}
*reply = args.A + args.B
return nil
}
func main() {
arith := new(Arith)
rpc.Register(arith)
listener, err := net.Listen("tcp", ":1234")
if err != nil {
panic(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go rpc.ServeCodec(jsonrpc.NewServerCodec(conn))
}
}
- second.go
// second.go
package main
import (
"fmt"
"net"
"net/rpc/jsonrpc"
)
// Args holds the arguments to be passed to the RPC method.
type Args struct {
A, B int
}
func main() {
//连接 RPC服务端
conn, err := net.Dial("tcp", "localhost:1234")
if err != nil {
panic(err)
}
defer conn.Close()
// 创建一个客户端
client := jsonrpc.NewClient(conn)
// 准备参数
args := Args{A: 1, B: 2}
var reply int
// 调用Add方法
err = client.Call("Arith.Add", &args, &reply)
if err != nil {
panic(err)
}
// Print the result
fmt.Printf("Result: %d + %d = %d\n", args.A, args.B, reply)
}
结果:
Result: 1 + 2 = 3