本章节主要讲解Go语言如何实现简易的rpc通讯。实现方式有http、tcp、json,本文只讲解http方式,更多请移步底部github。
client.php 源码:package main import ( "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") os.Exit(1) } serverAddress := os.Args[1] client, err := rpc.DialHTTP("tcp", serverAddress+":1234") if err != nil { log.Fatal("dialing:", err) } // Synchronous call args := Args{17, 8} var reply int err = client.Call("Math.Multiply", args, &reply) if err != nil { log.Fatal("Math error:", err) } fmt.Printf("Math: %d*%d=%d\n", args.A, args.B, reply) var quot Quotient err = client.Call("Math.Divide", args, ") if err != nil { log.Fatal("Math error:", err) } fmt.Printf("Math: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem) }server.go 源码:
package main import ( "errors" "fmt" "net/http" "net/rpc" ) type Args struct { A, B int } type Quotient struct { Quo, Rem int } type Math int func (t *Math) Multiply(args *Args, reply *int) error { *reply = args.A * args.B return nil } func (t *Math) 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() { math := new(Math) rpc.Register(math) rpc.HandleHTTP() err := http.ListenAndServe(":1234", nil) if err != nil { fmt.Println(err.Error()) } }
已有0条评论