這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
內建的gob
rpcserver
package mainimport ( "errors" "fmt" "net" "net/rpc" "os")type Args struct { A, B int}type Quotient struct { Quo, Rem int}type Arith intfunc (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) tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234") checkError(err) listener, err := net.ListenTCP("tcp", tcpAddr) checkError(err) /* rpc.Accept(listener) */ for { conn, err := listener.Accept() if err != nil { continue } rpc.ServeConn(conn) }}func checkError(err error) { if err != nil { fmt.Println("Fatal error ", err.Error()) os.Exit(1) }}
rpcclient
package mainimport ( "fmt" "log" "net/rpc" "os")type Args struct { A, B int}type Quotient struct { Quo, Rem int}func main() { if len(os.Args) != 2 { fmt.Println("Usage: ", os.Args[0], "server:port") os.Exit(1) } service := os.Args[1] client, err := rpc.Dial("tcp", service) if err != nil { log.Fatal("dialing:", err) } // Synchronous call args := Args{17, 8} var reply int err = client.Call("Arith.Multiply", args, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply) var quot Quotient err = client.Call("Arith.Divide", args, ") if err != nil { log.Fatal("arith error:", err) } fmt.Printf("Arith: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)}
測試
運行 ./server運行 ./client 127.0.0.1:1234