Implementing servers

There are a few classes to simplify server implementation with gevent. They all share the similar interface:

def handle(socket, address):
     print 'new connection!'

server = StreamServer(('', 1234), handle) # creates a new server
server.start() # start accepting new connections

At this point, any new connection accepted on will result in a new Greenlet spawned using handle function. To stop a server use stop() method.

In case of a WSGIServer, handle must be a WSGI application callable.

It is possible to limit the maximum number of concurrent connections, by passing a Pool instance:

pool = Pool(10000) # do not accept more than 10000 connections
server = StreamServer(('', 1234), handle, spawn=pool)

The serve_forever() method calls start() and then waits until interrupted or until the server is stopped.

The difference between wsgi.WSGIServer and pywsgi.WSGIServer is that the first one is very fast as it uses libevent’s http server implementation but it shares the issues that libevent-http has. In particular:

The pywsgi.WSGIServer does not have these limitations. In addition, gunicorn is a stand-alone server that supports gevent. Gunicorn has its own HTTP parser but can also use gevent.wsgi module.

More examples are available in the code repository:

Next page: gevent.server – TCP/SSL server