version: 1.10

package rpc

import "net/rpc"

Overview

Package rpc provides access to the exported methods of an object across a
network or other I/O connection. A server registers an object, making it visible
as a service with the name of the type of the object. After registration,
exported methods of the object will be accessible remotely. A server may
register multiple objects (services) of different types but it is an error to
register multiple objects of the same type.

Only methods that satisfy these criteria will be made available for remote
access; other methods will be ignored:

  1. - the method's type is exported.
  2. - the method is exported.
  3. - the method has two arguments, both exported (or builtin) types.
  4. - the method's second argument is a pointer.
  5. - the method has return type error.

In effect, the method must look schematically like

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

where T1 and T2 can be marshaled by encoding/gob. These requirements apply even
if a different codec is used. (In the future, these requirements may soften for
custom codecs.)

The method’s first argument represents the arguments provided by the caller; the
second argument represents the result parameters to be returned to the caller.
The method’s return value, if non-nil, is passed back as a string that the
client sees as if created by errors.New. If an error is returned, the reply
parameter will not be sent back to the client.

The server may handle requests on a single connection by calling ServeConn. More
typically it will create a network listener and call Accept or, for an HTTP
listener, HandleHTTP and http.Serve.

A client wishing to use the service establishes a connection and then invokes
NewClient on the connection. The convenience function Dial (DialHTTP) performs
both steps for a raw network connection (an HTTP connection). The resulting
Client object has two methods, Call and Go, that specify the service and method
to call, a pointer containing the arguments, and a pointer to receive the result
parameters.

The Call method waits for the remote call to complete while the Go method
launches the call asynchronously and signals completion using the Call
structure’s Done channel.

Unless an explicit codec is set up, package encoding/gob is used to transport
the data.

Here is a simple example. A server wishes to export an object of type Arith:

  1. package server
  2. import "errors"
  3. type Args struct {
  4. A, B int
  5. }
  6. type Quotient struct {
  7. Quo, Rem int
  8. }
  9. type Arith int
  10. func (t *Arith) Multiply(args *Args, reply *int) error {
  11. *reply = args.A * args.B
  12. return nil
  13. }
  14. func (t *Arith) Divide(args *Args, quo *Quotient) error {
  15. if args.B == 0 {
  16. return errors.New("divide by zero")
  17. }
  18. quo.Quo = args.A / args.B
  19. quo.Rem = args.A % args.B
  20. return nil
  21. }

The server calls (for HTTP service):

  1. arith := new(Arith)
  2. rpc.Register(arith)
  3. rpc.HandleHTTP()
  4. l, e := net.Listen("tcp", ":1234")
  5. if e != nil {
  6. log.Fatal("listen error:", e)
  7. }
  8. go http.Serve(l, nil)

At this point, clients can see a service “Arith” with methods “Arith.Multiply”
and “Arith.Divide”. To invoke one, a client first dials the server:

  1. client, err := rpc.DialHTTP("tcp", serverAddress + ":1234")
  2. if err != nil {
  3. log.Fatal("dialing:", err)
  4. }

Then it can make a remote call:

  1. // Synchronous call
  2. args := &server.Args{7,8}
  3. var reply int
  4. err = client.Call("Arith.Multiply", args, &reply)
  5. if err != nil {
  6. log.Fatal("arith error:", err)
  7. }
  8. fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)

or

  1. // Asynchronous call
  2. quotient := new(Quotient)
  3. divCall := client.Go("Arith.Divide", args, quotient, nil)
  4. replyCall := <-divCall.Done // will be equal to divCall
  5. // check errors, print, etc.

A server implementation will often provide a simple, type-safe wrapper for the
client.

The net/rpc package is frozen and is not accepting new features.

Index

Package files

client.go debug.go server.go

Constants

  1. const (
  2. // Defaults used by HandleHTTP
  3. DefaultRPCPath = "/_goRPC_"
  4. DefaultDebugPath = "/debug/rpc"
  5. )

Variables

  1. var DefaultServer = NewServer()

DefaultServer is the default instance of *Server.

  1. var ErrShutdown = errors.New("connection is shut down")

func Accept

  1. func Accept(lis net.Listener)

Accept accepts connections on the listener and serves requests to DefaultServer
for each incoming connection. Accept blocks; the caller typically invokes it in
a go statement.

func HandleHTTP

  1. func HandleHTTP()

HandleHTTP registers an HTTP handler for RPC messages to DefaultServer on
DefaultRPCPath and a debugging handler on DefaultDebugPath. It is still
necessary to invoke http.Serve(), typically in a go statement.

func Register

  1. func Register(rcvr interface{}) error

Register publishes the receiver’s methods in the DefaultServer.

func RegisterName

  1. func RegisterName(name string, rcvr interface{}) error

RegisterName is like Register but uses the provided name for the type instead of
the receiver’s concrete type.

func ServeCodec

  1. func ServeCodec(codec ServerCodec)

ServeCodec is like ServeConn but uses the specified codec to decode requests and
encode responses.

func ServeConn

  1. func ServeConn(conn io.ReadWriteCloser)

ServeConn runs the DefaultServer on a single connection. ServeConn blocks,
serving the connection until the client hangs up. The caller typically invokes
ServeConn in a go statement. ServeConn uses the gob wire format (see package
gob) on the connection. To use an alternate codec, use ServeCodec.

func ServeRequest

  1. func ServeRequest(codec ServerCodec) error

ServeRequest is like ServeCodec but synchronously serves a single request. It
does not close the codec upon completion.

type Call

  1. type Call struct {
  2. ServiceMethod string // The name of the service and method to call.
  3. Args interface{} // The argument to the function (*struct).
  4. Reply interface{} // The reply from the function (*struct).
  5. Error error // After completion, the error status.
  6. Done chan *Call // Strobes when call is complete.
  7. }

Call represents an active RPC.

type Client

  1. type Client struct {
  2. // contains filtered or unexported fields
  3. }

Client represents an RPC Client. There may be multiple outstanding Calls
associated with a single Client, and a Client may be used by multiple goroutines
simultaneously.

func Dial

  1. func Dial(network, address string) (*Client, error)

Dial connects to an RPC server at the specified network address.

func DialHTTP

  1. func DialHTTP(network, address string) (*Client, error)

DialHTTP connects to an HTTP RPC server at the specified network address
listening on the default HTTP RPC path.

func DialHTTPPath

  1. func DialHTTPPath(network, address, path string) (*Client, error)

DialHTTPPath connects to an HTTP RPC server at the specified network address and
path.

func NewClient

  1. func NewClient(conn io.ReadWriteCloser) *Client

NewClient returns a new Client to handle requests to the set of services at the
other end of the connection. It adds a buffer to the write side of the
connection so the header and payload are sent as a unit.

func NewClientWithCodec

  1. func NewClientWithCodec(codec ClientCodec) *Client

NewClientWithCodec is like NewClient but uses the specified codec to encode
requests and decode responses.

func (*Client) Call

  1. func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error

Call invokes the named function, waits for it to complete, and returns its error
status.

func (*Client) Close

  1. func (client *Client) Close() error

Close calls the underlying codec’s Close method. If the connection is already
shutting down, ErrShutdown is returned.

func (*Client) Go

  1. func (client *Client) Go(serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call

Go invokes the function asynchronously. It returns the Call structure
representing the invocation. The done channel will signal when the call is
complete by returning the same Call object. If done is nil, Go will allocate a
new channel. If non-nil, done must be buffered or Go will deliberately crash.

type ClientCodec

  1. type ClientCodec interface {
  2. // WriteRequest must be safe for concurrent use by multiple goroutines.
  3. WriteRequest(*Request, interface{}) error
  4. ReadResponseHeader(*Response) error
  5. ReadResponseBody(interface{}) error
  6.  
  7. Close() error
  8. }

A ClientCodec implements writing of RPC requests and reading of RPC responses
for the client side of an RPC session. The client calls WriteRequest to write a
request to the connection and calls ReadResponseHeader and ReadResponseBody in
pairs to read responses. The client calls Close when finished with the
connection. ReadResponseBody may be called with a nil argument to force the body
of the response to be read and then discarded.

type Request

  1. type Request struct {
  2. ServiceMethod string // format: "Service.Method"
  3. Seq uint64 // sequence number chosen by client
  4. // contains filtered or unexported fields
  5. }

Request is a header written before every RPC call. It is used internally but
documented here as an aid to debugging, such as when analyzing network traffic.

type Response

  1. type Response struct {
  2. ServiceMethod string // echoes that of the Request
  3. Seq uint64 // echoes that of the request
  4. Error string // error, if any.
  5. // contains filtered or unexported fields
  6. }

Response is a header written before every RPC return. It is used internally but
documented here as an aid to debugging, such as when analyzing network traffic.

type Server

  1. type Server struct {
  2. // contains filtered or unexported fields
  3. }

Server represents an RPC Server.

func NewServer

  1. func NewServer() *Server

NewServer returns a new Server.

func (*Server) Accept

  1. func (server *Server) Accept(lis net.Listener)

Accept accepts connections on the listener and serves requests for each incoming
connection. Accept blocks until the listener returns a non-nil error. The caller
typically invokes Accept in a go statement.

func (*Server) HandleHTTP

  1. func (server *Server) HandleHTTP(rpcPath, debugPath string)

HandleHTTP registers an HTTP handler for RPC messages on rpcPath, and a
debugging handler on debugPath. It is still necessary to invoke http.Serve(),
typically in a go statement.

func (*Server) Register

  1. func (server *Server) Register(rcvr interface{}) error

Register publishes in the server the set of methods of the receiver value that
satisfy the following conditions:

  1. - exported method of exported type
  2. - two arguments, both of exported type
  3. - the second argument is a pointer
  4. - one return value, of type error

It returns an error if the receiver is not an exported type or has no suitable
methods. It also logs the error using package log. The client accesses each
method using a string of the form “Type.Method”, where Type is the receiver’s
concrete type.

func (*Server) RegisterName

  1. func (server *Server) RegisterName(name string, rcvr interface{}) error

RegisterName is like Register but uses the provided name for the type instead of
the receiver’s concrete type.

func (*Server) ServeCodec

  1. func (server *Server) ServeCodec(codec ServerCodec)

ServeCodec is like ServeConn but uses the specified codec to decode requests and
encode responses.

func (*Server) ServeConn

  1. func (server *Server) ServeConn(conn io.ReadWriteCloser)

ServeConn runs the server on a single connection. ServeConn blocks, serving the
connection until the client hangs up. The caller typically invokes ServeConn in
a go statement. ServeConn uses the gob wire format (see package gob) on the
connection. To use an alternate codec, use ServeCodec.

func (*Server) ServeHTTP

  1. func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements an http.Handler that answers RPC requests.

func (*Server) ServeRequest

  1. func (server *Server) ServeRequest(codec ServerCodec) error

ServeRequest is like ServeCodec but synchronously serves a single request. It
does not close the codec upon completion.

type ServerCodec

  1. type ServerCodec interface {
  2. ReadRequestHeader(*Request) error
  3. ReadRequestBody(interface{}) error
  4. // WriteResponse must be safe for concurrent use by multiple goroutines.
  5. WriteResponse(*Response, interface{}) error
  6.  
  7. Close() error
  8. }

A ServerCodec implements reading of RPC requests and writing of RPC responses
for the server side of an RPC session. The server calls ReadRequestHeader and
ReadRequestBody in pairs to read requests from the connection, and it calls
WriteResponse to write a response back. The server calls Close when finished
with the connection. ReadRequestBody may be called with a nil argument to force
the body of the request to be read and discarded.

type ServerError

  1. type ServerError string

ServerError represents an error that has been returned from the remote side of
the RPC connection.

func (ServerError) Error

  1. func (e ServerError) Error() string

Subdirectories