快捷搜索: 长连接 前端 源码 pan

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
", 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 pc_client>rpc_client.exe please input two number!

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

D:GoProj pc_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

经验分享 程序员 微信小程序 职场和发展