golang two ways to call rpc

  • 2020-06-01 09:58:33
  • OfStack

This article illustrates two ways to call rpc using golang as an example. I will share it with you for your reference as follows:

golang's rpc is called in two ways, one of which is given in the rpc example:

package main
import (
        "net/rpc"
        "net/http"
        "log"
        "net"
        "time"
)
type Args struct {
        A, B int
}
type Arith int
func (t *Arith) Multiply(args *Args, reply *([]string)) error {
        *reply = append(*reply, "test")
        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)
        }
        go http.Serve(l, nil)
        time.Sleep(5 * time.Second)
        client, err := rpc.DialHTTP("tcp", "127.0.0.1" + ":1234")
        if err != nil {
                log.Fatal("dialing:", err)
        }
        args := &Args{7,8}
        reply := make([]string, 10)
        err = client.Call("Arith.Multiply", args, &reply)
        if err != nil {
                log.Fatal("arith error:", err)
        }
        log.Println(reply)
}

The other is to use NewServer

This is when rpc is already registered and another one will be used. That is, one server can only register one type in DefaultRPC.

When Server USES rpc.NewServer, client also needs to be changed

package main
import (
        "net/rpc"
        //"net/http"
        "log"
        "net"
        "time"
)
type Args struct {
        A, B int
}
type Arith int
func (t *Arith) Multiply(args *Args, reply *([]string)) error {
        *reply = append(*reply, "test")
        return nil
}
func main() {
        newServer := rpc.NewServer()
        newServer.Register(new(Arith))
        l, e := net.Listen("tcp", "127.0.0.1:1234") // any available address
        if e != nil {
                log.Fatalf("net.Listen tcp :0: %v", e)
        }
        go newServer.Accept(l)
        newServer.HandleHTTP("/foo", "/bar")
        time.Sleep(2 * time.Second)
        address, err := net.ResolveTCPAddr("tcp", "127.0.0.1:1234")
        if err != nil {
                panic(err)
        }
        conn, _ := net.DialTCP("tcp", nil, address)
        defer conn.Close()
        client := rpc.NewClient(conn)
        defer client.Close()
        args := &Args{7,8}
        reply := make([]string, 10)
        err = client.Call("Arith.Multiply", args, &reply)
        if err != nil {
                log.Fatal("arith error:", err)
        }
        log.Println(reply)
}

In the second example

newServer.HandleHTTP("/foo", "/bar")

You can set it any way you want, but the first example actually sets the default two

reply is also shown here as an example of []slice

I hope this article has been helpful to you in programming Go.


Related articles: