websocket – Websocket Server

This module provides a simple way to create a websocket server. It works with a few tweaks in the wsgi module that allow websockets to coexist with other WSGI applications.

To create a websocket server, simply decorate a handler method with WebSocketWSGI and use it as a wsgi application:

from eventlet import wsgi, websocket
import eventlet

def hello_world(ws):
    ws.send("hello world")

wsgi.server(eventlet.listen(('', 8090)), hello_world)


Please see graceful termination warning in server() documentation

You can find a slightly more elaborate version of this code in the file examples/websocket.py.

As of version 0.9.13, eventlet.websocket supports SSL websockets; all that’s necessary is to use an SSL wsgi server.


The web socket spec is still under development, and it will be necessary to change the way that this module works in response to spec changes.

class eventlet.websocket.WebSocket(sock, environ, version=76)

A websocket object that handles the details of serialization/deserialization to the socket.

The primary way to interact with a WebSocket object is to call send() and wait() in order to pass messages back and forth with the browser. Also available are the following properties:


The path value of the request. This is the same as the WSGI PATH_INFO variable, but more convenient.


The value of the Websocket-Protocol header.


The value of the ‘Origin’ header.


The full WSGI environment for this request.


Forcibly close the websocket; generally it is preferable to return from the handler method.


Send a message to the browser.

message should be convertable to a string; unicode objects should be encodable as utf-8. Raises socket.error with errno of 32 (broken pipe) if the socket has already been closed by the client.


Waits for and deserializes messages.

Returns a single message; the oldest not yet processed. If the client has already closed the connection, returns None. This is different from normal socket behavior because the empty string is a valid websocket message.

class eventlet.websocket.WebSocketWSGI(handler, max_frame_length=8388608)

Wraps a websocket handler function in a WSGI application.

Use it like this:

def my_handler(ws):
    from_browser = ws.wait()
    ws.send("from server")

The single argument to the function will be an instance of WebSocket. To close the socket, simply return from the function. Note that the server will log the websocket request at the time of closure.

An optional argument max_frame_length can be given, which will set the maximum incoming uncompressed payload length of a frame. By default, this is set to 8MiB. Note that excessive values here might create a DOS attack vector.