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(('127.0.0.1', 1234), handle) # creates a new server server.start() # start accepting new connections
At this point, any new connection accepted on 127.0.0.1:1234 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(('127.0.0.1', 1234), handle, spawn=pool) server.serve_forever()
The server_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:
More examples are available in the code repository:
Next page: gevent.server – TCP/SSL server