8.4 RPC

In previous sections we talked about how to write network applications based on Sockets and HTTP. We learned that both of them use the “information exchange” model, in which clients send requests and servers respond to them. This kind of data exchange is based on a specific format so that both sides are able to communicate with one another. However, many independent applications do not use this model, but instead call services just like they would call normal functions.

RPC was intended to be the function call mode for networked systems. Clients execute RPCs like they call native functions, except they package the function parameters and send them through the network to the server. The server can then unpack these parameters and process the request, executing the results back to the client.

In computer science, a remote procedure call (RPC) is a type of inter-process communication that allows a computer program to cause a subroutine or procedure to execute in another address space (commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction. That is, the programmer writes essentially the same code whether the subroutine is local to the executing program, or remote. When the software in question uses object-oriented principles, RPC is called remote invocation or remote method invocation.

RPC working principle

8.4. RPC - 图1

Figure 8.8 RPC working principle

Normally, an RPC call from client to server has the following ten steps:

    1. Call the client handle, execute transfer arguments.
    1. Call local system kernel to send network messages.
    1. Send messages to remote hosts.
    1. The server receives handle and arguments.
    1. Execute remote processes.
    1. Return execution result to corresponding handle.
    1. The server handle calls remote system kernel.
    1. Messages sent back to local system kernel.
    1. The client handle receives messages from system kernel.
    1. The client gets results from corresponding handle.

Go RPC

Go has official support for RPC in its standard library on three levels, which are TCP, HTTP and JSON RPC. Note that Go RPC is not like other traditional RPC systems. It requires you to use Go applications on both client and server sides because it encodes content using Gob.

Functions of Go RPC must abide by the following rules for remote access, otherwise the corresponding calls will be ignored.

  • Functions are exported (capitalized).
  • Functions must have two arguments with exported types.
  • The first argument is for receiving from the client, and the second one has to be a pointer and is for replying to the client.
  • Functions must have a return value of error type.

For example:

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

Where T, T1 and T2 must be able to be encoded by the package/gob package.

Any kind of RPC has to go through a network to transfer data. Go RPC can either use HTTP or TCP. The benefits of using HTTP is that you can reuse some functions from the net/http package.

HTTP RPC

HTTP server side code:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "net/rpc"
  7. )
  8. type Args struct {
  9. A, B int
  10. }
  11. type Quotient struct {
  12. Quo, Rem int
  13. }
  14. type Arith int
  15. func (t *Arith) Multiply(args *Args, reply *int) error {
  16. *reply = args.A * args.B
  17. return nil
  18. }
  19. func (t *Arith) Divide(args *Args, quo *Quotient) error {
  20. if args.B == 0 {
  21. return errors.New("divide by zero")
  22. }
  23. quo.Quo = args.A / args.B
  24. quo.Rem = args.A % args.B
  25. return nil
  26. }
  27. func main() {
  28. arith := new(Arith)
  29. rpc.Register(arith)
  30. rpc.HandleHTTP()
  31. err := http.ListenAndServe(":1234", nil)
  32. if err != nil {
  33. fmt.Println(err.Error())
  34. }
  35. }

We registered a RPC service of Arith, then registered this service on HTTP through rpc.HandleHTTP. After that, we are able to transfer data through HTTP.

Client side code:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/rpc"
  6. "os"
  7. )
  8. type Args struct {
  9. A, B int
  10. }
  11. type Quotient struct {
  12. Quo, Rem int
  13. }
  14. func main() {
  15. if len(os.Args) != 2 {
  16. fmt.Println("Usage: ", os.Args[0], "server")
  17. os.Exit(1)
  18. }
  19. serverAddress := os.Args[1]
  20. client, err := rpc.DialHTTP("tcp", serverAddress+":1234")
  21. if err != nil {
  22. log.Fatal("dialing:", err)
  23. }
  24. // Synchronous call
  25. args := Args{17, 8}
  26. var reply int
  27. err = client.Call("Arith.Multiply", args, &reply)
  28. if err != nil {
  29. log.Fatal("arith error:", err)
  30. }
  31. fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)
  32. var quot Quotient
  33. err = client.Call("Arith.Divide", args, &quot)
  34. if err != nil {
  35. log.Fatal("arith error:", err)
  36. }
  37. fmt.Printf("Arith: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)
  38. }

We compile the client and the server side code separately then start the server and client. You’ll then have something similar as follows after you input some data.

  1. $ ./http_c localhost
  2. Arith: 17*8=136
  3. Arith: 17/8=2 remainder 1

As you can see, we defined a struct for the return type. We use it as type of function argument on the server side, and as the type of the second and third arguments on the client client.Call. This call is very important. It has three arguments, where the first one is the name of the function that is going to be called, the second is the argument you want to pass, and the last one is the return value (of pointer type). So far we see that it’s easy to implement RPC in Go.

TCP RPC

Let’s try the RPC that is based on TCP, here is the server side code:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/rpc"
  7. "os"
  8. )
  9. type Args struct {
  10. A, B int
  11. }
  12. type Quotient struct {
  13. Quo, Rem int
  14. }
  15. type Arith int
  16. func (t *Arith) Multiply(args *Args, reply *int) error {
  17. *reply = args.A * args.B
  18. return nil
  19. }
  20. func (t *Arith) Divide(args *Args, quo *Quotient) error {
  21. if args.B == 0 {
  22. return errors.New("divide by zero")
  23. }
  24. quo.Quo = args.A / args.B
  25. quo.Rem = args.A % args.B
  26. return nil
  27. }
  28. func main() {
  29. arith := new(Arith)
  30. rpc.Register(arith)
  31. tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
  32. checkError(err)
  33. listener, err := net.ListenTCP("tcp", tcpAddr)
  34. checkError(err)
  35. for {
  36. conn, err := listener.Accept()
  37. if err != nil {
  38. continue
  39. }
  40. rpc.ServeConn(conn)
  41. }
  42. }
  43. func checkError(err error) {
  44. if err != nil {
  45. fmt.Println("Fatal error ", err.Error())
  46. os.Exit(1)
  47. }
  48. }

The difference between HTTP RPC and TCP RPC is that we have to control connections by ourselves if we use TCP RPC, then pass connections to RPC for processing.

As you may have guessed, this is a blocking pattern. You are free to use goroutines to extend this application as a more advanced experiment.

The client side code:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/rpc"
  6. "os"
  7. )
  8. type Args struct {
  9. A, B int
  10. }
  11. type Quotient struct {
  12. Quo, Rem int
  13. }
  14. func main() {
  15. if len(os.Args) != 2 {
  16. fmt.Println("Usage: ", os.Args[0], "server:port")
  17. os.Exit(1)
  18. }
  19. service := os.Args[1]
  20. client, err := rpc.Dial("tcp", service)
  21. if err != nil {
  22. log.Fatal("dialing:", err)
  23. }
  24. // Synchronous call
  25. args := Args{17, 8}
  26. var reply int
  27. err = client.Call("Arith.Multiply", args, &reply)
  28. if err != nil {
  29. log.Fatal("arith error:", err)
  30. }
  31. fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)
  32. var quot Quotient
  33. err = client.Call("Arith.Divide", args, &quot)
  34. if err != nil {
  35. log.Fatal("arith error:", err)
  36. }
  37. fmt.Printf("Arith: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)
  38. }

The only difference in the client side code is that HTTP clients use DialHTTP whereas TCP clients use Dial(TCP).

JSON RPC

JSON RPC encodes data to JSON instead of gob. Let’s see an example of a Go JSON RPC on the server:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/rpc"
  7. "net/rpc/jsonrpc"
  8. "os"
  9. )
  10. type Args struct {
  11. A, B int
  12. }
  13. type Quotient struct {
  14. Quo, Rem int
  15. }
  16. type Arith int
  17. func (t *Arith) Multiply(args *Args, reply *int) error {
  18. *reply = args.A * args.B
  19. return nil
  20. }
  21. func (t *Arith) Divide(args *Args, quo *Quotient) error {
  22. if args.B == 0 {
  23. return errors.New("divide by zero")
  24. }
  25. quo.Quo = args.A / args.B
  26. quo.Rem = args.A % args.B
  27. return nil
  28. }
  29. func main() {
  30. arith := new(Arith)
  31. rpc.Register(arith)
  32. tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
  33. checkError(err)
  34. listener, err := net.ListenTCP("tcp", tcpAddr)
  35. checkError(err)
  36. for {
  37. conn, err := listener.Accept()
  38. if err != nil {
  39. continue
  40. }
  41. jsonrpc.ServeConn(conn)
  42. }
  43. }
  44. func checkError(err error) {
  45. if err != nil {
  46. fmt.Println("Fatal error ", err.Error())
  47. os.Exit(1)
  48. }
  49. }

JSON RPC is based on TCP and doesn’t support HTTP yet.

The client side code:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/rpc/jsonrpc"
  6. "os"
  7. )
  8. type Args struct {
  9. A, B int
  10. }
  11. type Quotient struct {
  12. Quo, Rem int
  13. }
  14. func main() {
  15. if len(os.Args) != 2 {
  16. fmt.Println("Usage: ", os.Args[0], "server:port")
  17. log.Fatal(1)
  18. }
  19. service := os.Args[1]
  20. client, err := jsonrpc.Dial("tcp", service)
  21. if err != nil {
  22. log.Fatal("dialing:", err)
  23. }
  24. // Synchronous call
  25. args := Args{17, 8}
  26. var reply int
  27. err = client.Call("Arith.Multiply", args, &reply)
  28. if err != nil {
  29. log.Fatal("arith error:", err)
  30. }
  31. fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)
  32. var quot Quotient
  33. err = client.Call("Arith.Divide", args, &quot)
  34. if err != nil {
  35. log.Fatal("arith error:", err)
  36. }
  37. fmt.Printf("Arith: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)
  38. }

Summary

Go has good support for HTTP, TPC and JSON RPC implementation which allow us to easily develop distributed web applications; however, it is regrettable that Go doesn’t have built-in support for SOAP RPC, although some open source third-party packages do offer this.