Go RPC return value

The Go language RPC definition format is as follows:

func (t T) MethodName(argType T1, replyType T2) error

The first parameter is the received parameter, the second parameter is the parameter returned to the client, and the second parameter must
be a pointer type

If the server-side RPC function returns an error, that is, error is not nil, the second parameter will not return any information.

Examples are as follows.

server side

package main

import (
    "fmt"
    "net"
    "net/rpc"
    "net/rpc/jsonrpc"
)

type Counter struct {
    Sum int
}

func (this *Counter) Add(i int, r *int) error {

    if i < 0 {
        *r = -1
        return fmt.Errorf("data format incorrect")
    }


    this.Sum += i
    *r = this.Sum
    fmt.Printf("i: %v\n", i)
    return nil
}

func NewJsonRpcSocketServer() {

    rpc.Register(new(Counter))

    l, err := net.Listen("tcp", ":3333")
    if err != nil {
        fmt.Printf("Listener tcp err: %s", err)
        return
    }

    for {
        fmt.Println("wating...")
        conn, err := l.Accept()
        if err != nil {
            fmt.Sprintf("accept connection err: %s\n", conn)
        }
        go jsonrpc.ServeConn(conn)
    }

}

func main() {

    NewJsonRpcSocketServer()
}

When the parameter is less than 0, the server returns an error and sets the repoy to -1.

client side

package main

import (
    "fmt"
    "net"
    "net/rpc/jsonrpc"
    "time"
)


func main() {

     NewJsonRpcSocketClient()
}


func NewJsonRpcSocketClient() {

    timeout := time.Second*30
    conn, err := net.DialTimeout("tcp", "127.0.0.1:3333", timeout)
    if err != nil {
        fmt.Printf("create client err:%s\n", err)
        return
    }
    defer conn.Close()

    client := jsonrpc.NewClient(conn)
    var reply int
    err = client.Call("Counter.Add", -10, &reply)
    if err != nil {
    
        fmt.Println("error:", err, "reply:", reply)
    return
    }

    fmt.Printf("reply: %d, err: %v\n", reply, err)

}

The incoming parameter on the client side is less than 0. At this time, the client output:

error: data format incorrect reply: 0

reply is still the default value, and the information set on the server side is not returned to the client.
The results are verified.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325116364&siteId=291194637