Go语言 RPC通信示例

服务端程序

package main

import (
    "errors"
    "fmt"
    "log"
    "net"
    "net/http"
    "net/rpc"
)

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

    fmt.Println("Multiply", args.A, args.B)
    return nil
}

func (t *Arith) Divide(args *Args, quo *Quotient) error {
    fmt.Println("Divide", Args.A, Args.B)

    if args.B == 0 {
        return errors.New("divide by zero")
    }
    quo.Quo = args.A / args.B
    quo.Rem = args.A % args.B

    fmt.Println("Divide", quo.Quo, quo.Rem)

    return nil
}

func main() {
    arith := new(Arith)
    rpc.Register(arith)
    rpc.HandleHTTP()
    l, e := net.Listen("tcp", ":1234")
    if e != nil {
        log.Fatal("listen error:", e)
    }
    http.Serve(l, nil)
}

客户端程序

package main

import (
    "fmt"
    "log"
    "net/rpc"
    "os"
    "strconv"
)

type Args struct {
    A, B int
}

type Quotient struct {
    Quo, Rem int
}

func main() {

    if len(os.Args) != 3 {
        fmt.Println("please input two number!")
        os.Exit(1)
    }
    strnum1 := os.Args[1]
    strnum2 := os.Args[2]

    num1, error := strconv.Atoi(strnum1)
    if error != nil {
        fmt.Println("error number!")
        os.Exit(1)
    }

    num2, error2 := strconv.Atoi(strnum2)
    if error2 != nil {
        fmt.Println("error number!")
        os.Exit(1)
    }

    client, err := rpc.DialHTTP("tcp", "127.0.0.1:1234")
    if err != nil {
        log.Fatal("dialing:", err)
    }

    // Synchronous call
    args := &Args{num1, num2}

    fmt.Println("Multiply", args.A, args.B)

    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)

    // Asynchronous call
    quotient := new(Quotient)

    fmt.Println("Divide", args.A, args.B)

    divCall := client.Go("Arith.Divide", args, quotient, nil)
    replyCall := <-divCall.Done // will be equal to divCall
    if replyCall.Error != nil {
        log.Fatal("arith error:", replyCall.Error)
    }
    fmt.Printf("Arith: %d/%d=%d...%d", args.A, args.B, quotient.Quo, quotient.Rem)
    // check errors, print, etc.
}

输入测试

D:\GoProj\rpc_client>rpc_client.exe
please input two number!

D:\GoProj\rpc_client>rpc_client.exe 30 6
Multiply 30 6
Arith: 30*6=180
Divide 30 6
Arith: 30/6=5…0

D:\GoProj\rpc_client>rpc_client.exe 30 0
Multiply 30 0
Arith: 30*0=0
Divide 30 0
2018/01/21 14:52:53 arith error:divide by zero

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值