# gevent

# Implementing servers

There are a few classes to simplify server implementation with gevent. They all share a similar interface, inherited from `BaseServer`:

    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 `gevent.Greenlet` spawned running the handle function. To stop a server use `BaseServer.stop()` method.

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

It is possible to limit the maximum number of concurrent connections, by passing a `gevent.pool.Pool` instance. In addition, passing a pool allows the `BaseServer.stop()` method to kill requests that are in progress:

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

Tip

If you don’t want to limit concurrency, but you do want to be able to kill outstanding requests, use a pool created with a size of `None`.

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

The `gevent.pywsgi` module contains an implementation of a PEP 3333 `WSGI server`. In addition, gunicorn is a stand-alone server that supports gevent.

## API Reference

- gevent.baseserver – Base class for implementing servers
- gevent.server – TCP/SSL server
- gevent.pywsgi – A pure-Python, gevent-friendly WSGI server

## Examples

More examples are available:

- Example echoserver.py - demonstrates `gevent.server.StreamServer`
- Example wsgiserver.py - demonstrates `gevent.pywsgi.WSGIServer`
- Example wsgiserver_ssl.py - demonstrates `WSGIServer with ssl`

Next page: Name Resolution (DNS)