Creating an RPC server

Let us create a simple RPC server that sends the UTC server time back to the RPC client. First, we start with the server.

The RPC server and RPC client should agree upon two things:

  1. Arguments passed
  2. Value returned

The types for the preceding two parameters should exactly match for both server and client:

package main
import (
"log"
"net"
"net/http"
"net/rpc"
"time"
)
type Args struct{}
type TimeServer int64
func (t *TimeServer) GiveServerTime(args *Args, reply *int64) error {
// Fill reply pointer to send the data back
*reply = time.Now().Unix()
return nil
}
func main() {
// Create a new RPC server
timeserver := new(TimeServer)
// Register RPC server
rpc.Register(timeserver)
rpc.HandleHTTP()
// Listen for requests on port 1234
l, e := net.Listen("tcp", ":1234")
if e != nil {
log.Fatal("listen error:", e)
}
http.Serve(l, nil)
}

We first create the Args struct. This holds information about arguments passed from the client (RPC) to the server. Then, we created a TimeServer number to register with the rpc.Register. Here, the server wishes to export an object of type TimeServer(int64). HandleHTTP registers an HTTP handler for RPC messages to DefaultServer. Then we started a TCP server that listens on port 1234. The http.Serve function is used to serve it as a running program. GiveServerTime is the function that will be called by the client, and the current server time is returned. 

There are a few points to note from the preceding example:

  • GiveServerTime takes the Args object as the first argument and a reply pointer object
  • It sets the reply pointer object but does not return anything except an error
  • The Args struct here has no fields because this server is not expecting the client to send any arguments

Before running this program, let us write the RPC client, too. Both can be run simultaneously.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.239.166