methods used pkg-functions
For a function to be called remotely for RPC
- should be method i.e., should have receiver as per Go
- should be public (name starts with uppercase)
- should have 2 args
- 1st arg can be interpreted as request body
- 2nd arg is pointer to response body struct, called as
reply
- return
errortype- when method reaches end return
nil
- when method reaches end return
Now we can call our struct/type which acts as receiver for these procedures/methods
Server
-
create obj from struct which can be called remotely
-
start listening
:port(this step can be done afterwards) -
server way
- server obj need to be created
- register struct obj with rpc server
- in an infinite loop, continuously
- accept connections from listener with
Accept() - server connection with server obj
- accept connections from listener with
-
raw-dogging way
- register struct obj with
net/rpc - handle http and start serving
// ignore err handling var obj = new(type) lis, err := net.Listen("tcp", ":port") defer lis.close() // server way svr := rpc.NewServer() svr.Register(obj) for { conn, err := lis.Accept() svr.ServeConn(conn) } // raw-dogging way rpc.Register(obj) rpc.HandleHTTP() http.Serve(lis, nil) // either way, rpc will be served on :port - register struct obj with
Client
- we’ll have same types/structs as used in server
- additional to those,
reqBodyandrespstruct(s) should be created accordingly - response of function call will in
resp
client, err := rpc.DialHTTP("tcp", ":port")
client.Call("Type.Method", reqBody, &resp)