Go RPC返回值

Go 语言RPC定义格式如下:

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

第一个参数是接收的参数,第二个参数是返回给客户端的参数,第二个参数必
须是指针类型的

如果Server端RPC函数返回错误,即error不为nil,第二个参数不会返回任何信息。

例子如下。

server端

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
", 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
", conn)
        }
        go jsonrpc.ServeConn(conn)
    }

}

func main() {

	NewJsonRpcSocketServer()
}

server端对于参数小于0的情况,返回错误, 并把repoy设置为-1。

client端

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
", 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
", reply, err)

}

client端传入参数小于0,此时client output:

error: data format incorrect reply: 0

reply仍然是默认值,server端设置的信息没有返回给client。
结果得到验证。

原文地址:https://www.cnblogs.com/lanyangsh/p/8974831.html