Go语言学习之TCP RPC

来源:互联网 发布:编译c 的软件 编辑:程序博客网 时间:2024/06/16 11:00

server

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("divede 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")    if err != nil {        fmt.Println("Fatal error:", err)        os.Exit(1)    }    listener, err := net.ListenTCP("tcp", tcpAddr)    if err != nil {        fmt.Println("Fatal error:", err)        os.Exit(1)    }    for {        conn, err := listener.Accept()        if err != nil {            continue        }        rpc.ServeConn(conn)    }}

client

package mainimport (    "fmt"    "log"    "net/rpc")type Args struct {    A, B int}type Quotient struct {    Quo, Rem int}func main() {    service := "127.0.0.1:1234"    client, err := rpc.Dial("tcp", service)    if err != nil {        log.Fatal("dialing:", err)    }    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, &quot)    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)}

rpc原理

http://blog.csdn.net/libinbin_1014/article/details/73302757

原创粉丝点击