Server implementations

Like RPC Client, servers are top-level instances that most user code should interact with. They provide runnable functions that are combined with transports, protocols and dispatchers to form a complete RPC system.

Server definition.

Defines and implements a single-threaded, single-process, synchronous server.

class tinyrpc.server.RPCServer(transport: tinyrpc.transports.ServerTransport, protocol: tinyrpc.protocols.RPCProtocol, dispatcher: tinyrpc.dispatch.RPCDispatcher)

High level RPC server.

The server is completely generic only assuming some form of RPC communication is intended. Protocol, data transport and method dispatching are injected into the server object.

  • transport (ServerTransport) – The data transport mechanism to use.
  • protocol (RPCProtocol) – The RPC protocol to use.
  • dispatcher (RPCDispatcher) – The dispatching mechanism to use.
receive_one_message() → None

Handle a single request.

Polls the transport for a new message.

After a new message has arrived _spawn() is called with a handler function and arguments to handle the request.

The handler function will try to decode the message using the supplied protocol, if that fails, an error response will be sent. After decoding the message, the dispatcher will be asked to handle the resulting request and the return value (either an error or a result) will be sent back to the client using the transport.

serve_forever() → None

Handle requests forever.

Starts the server loop; continuously calling receive_one_message() to process the next incoming request.

trace = None

Trace incoming and outgoing messages.

When this attribute is set to a callable this callable will be called directly after a message has been received and immediately after a reply is sent. The callable should accept three positional parameters:

  • direction (str) – Either ‘–>’ for incoming or ‘<–’ for outgoing data.
  • context (any) – The context returned by receive_message().
  • message (bytes) – The message itself.


def my_trace(direction, context, message):
    logger.debug('%s%s', direction, message)

server = RPCServer(transport, protocol, dispatcher)
server.trace = my_trace

will log all incoming and outgoing traffic of the RPC service.

Note that the message will be the data stream that is transported, not the interpreted meaning of that data. It is therefore possible that the binary stream is unreadable without further translation.

class tinyrpc.server.gevent.RPCServerGreenlets

Asynchronous RPCServer.

This implementation of RPCServer uses gevent.spawn() to spawn new client handlers, result in asynchronous handling of clients using greenlets.