gevent.server – TCP/SSL server

class StreamServer(listener, handle=None, backlog=None, spawn='default', **ssl_args)

Bases: gevent.baseserver.BaseServer

A generic TCP server.

Accepts connections on a listening socket and spawns user-provided handle function for each connection with 2 arguments: the client socket and the client address.

Note that although the errors in a successfully spawned handler will not affect the server or other connections, the errors raised by accept() and spawn cause the server to stop accepting for a short amount of time. The exact period depends on the values of min_delay and max_delay attributes.

The delay starts with min_delay and doubles with each successive error until it reaches max_delay. A successful accept() resets the delay to min_delay again.

See BaseServer for information on defining the handle function and important restrictions on it.

SSL Support

The server can optionally work in SSL mode when given the correct keyword arguments. (That is, the presence of any keyword arguments will trigger SSL mode.) On Python 2.7.9 and later (any Python version that supports the ssl.SSLContext), this can be done with a configured SSLContext. On any Python version, it can be done by passing the appropriate arguments for ssl.wrap_socket().

The incoming socket will be wrapped into an SSL socket before being passed to the handle function.

If the ssl_context keyword argument is present, it should contain an ssl.SSLContext. The remaining keyword arguments are passed to the ssl.SSLContext.wrap_socket() method of that object. Depending on the Python version, supported arguments may include:

  • server_hostname
  • suppress_ragged_eofs
  • do_handshake_on_connect

Caution

When using an SSLContext, it should either be imported from gevent.ssl, or the process needs to be monkey-patched. If the process is not monkey-patched and you pass the standard library SSLContext, the resulting client sockets will not cooperate with gevent.

Otherwise, keyword arguments are assumed to apply to ssl.wrap_socket(). These keyword arguments bay include:

  • keyfile
  • certfile
  • cert_reqs
  • ssl_version
  • ca_certs
  • suppress_ragged_eofs
  • do_handshake_on_connect
  • ciphers

Changed in version 1.2a2: Add support for the ssl_context keyword argument.

class DatagramServer(*args, **kwargs)

Bases: gevent.baseserver.BaseServer

A UDP server

Next page: gevent.pywsgi – A pure-Python, gevent-friendly WSGI server