API Reference

class engineio.Client(logger=False, json=None, request_timeout=5, http_session=None, ssl_verify=True, handle_sigint=True, websocket_extra_options=None)

An Engine.IO client.

This class implements a fully compliant Engine.IO web client with support for websocket and long-polling transports.

Parameters:
  • logger – To enable logging set to True or pass a logger object to use. To disable logging set to False. The default is False. Note that fatal errors are logged even when logger is False.

  • json – An alternative json module to use for encoding and decoding packets. Custom json modules must have dumps and loads functions that are compatible with the standard library versions.

  • request_timeout – A timeout in seconds for requests. The default is 5 seconds.

  • http_session – an initialized requests.Session object to be used when sending requests to the server. Use it if you need to add special client options such as proxy servers, SSL certificates, custom CA bundle, etc.

  • ssl_verifyTrue to verify SSL certificates, or False to skip SSL certificate verification, allowing connections to servers with self signed certificates. The default is True.

  • handle_sigint – Set to True to automatically handle disconnection when the process is interrupted, or to False to leave interrupt handling to the calling application. Interrupt handling can only be enabled when the client instance is created in the main thread.

  • websocket_extra_options – Dictionary containing additional keyword arguments passed to websocket.create_connection().

connect(url, headers=None, transports=None, engineio_path='engine.io')

Connect to an Engine.IO server.

Parameters:
  • url – The URL of the Engine.IO server. It can include custom query string parameters if required by the server.

  • headers – A dictionary with custom headers to send with the connection request.

  • transports – The list of allowed transports. Valid transports are 'polling' and 'websocket'. If not given, the polling transport is connected first, then an upgrade to websocket is attempted.

  • engineio_path – The endpoint where the Engine.IO server is installed. The default value is appropriate for most cases.

Example usage:

eio = engineio.Client()
eio.connect('http://localhost:5000')
wait()

Wait until the connection with the server ends.

Client applications can use this function to block the main thread during the life of the connection.

send(data)

Send a message to the server.

Parameters:

data – The data to send to the server. Data can be of type str, bytes, list or dict. If a list or dict, the data will be serialized as JSON.

disconnect(abort=False)

Disconnect from the server.

Parameters:

abort – If set to True, do not wait for background tasks associated with the connection to end.

start_background_task(target, *args, **kwargs)

Start a background task.

This is a utility function that applications can use to start a background task.

Parameters:
  • target – the target function to execute.

  • args – arguments to pass to the function.

  • kwargs – keyword arguments to pass to the function.

This function returns an object that represents the background task, on which the join() method can be invoked to wait for the task to complete.

sleep(seconds=0)

Sleep for the requested amount of time.

create_queue(*args, **kwargs)

Create a queue object.

create_event(*args, **kwargs)

Create an event object.

on(event, handler=None)

Register an event handler.

Parameters:
  • event – The event name. Can be 'connect', 'message' or 'disconnect'.

  • handler – The function that should be invoked to handle the event. When this parameter is not given, the method acts as a decorator for the handler function.

Example usage:

# as a decorator:
@eio.on('connect')
def connect_handler():
    print('Connection request')

# as a method:
def message_handler(msg):
    print('Received message: ', msg)
    eio.send('response')
eio.on('message', message_handler)
transport()

Return the name of the transport currently in use.

The possible values returned by this function are 'polling' and 'websocket'.

class engineio.AsyncClient(logger=False, json=None, request_timeout=5, http_session=None, ssl_verify=True, handle_sigint=True, websocket_extra_options=None)

An Engine.IO client for asyncio.

This class implements a fully compliant Engine.IO web client with support for websocket and long-polling transports, compatible with the asyncio framework on Python 3.5 or newer.

Parameters:
  • logger – To enable logging set to True or pass a logger object to use. To disable logging set to False. The default is False. Note that fatal errors are logged even when logger is False.

  • json – An alternative json module to use for encoding and decoding packets. Custom json modules must have dumps and loads functions that are compatible with the standard library versions.

  • request_timeout – A timeout in seconds for requests. The default is 5 seconds.

  • http_session – an initialized aiohttp.ClientSession object to be used when sending requests to the server. Use it if you need to add special client options such as proxy servers, SSL certificates, etc.

  • ssl_verifyTrue to verify SSL certificates, or False to skip SSL certificate verification, allowing connections to servers with self signed certificates. The default is True.

  • handle_sigint – Set to True to automatically handle disconnection when the process is interrupted, or to False to leave interrupt handling to the calling application. Interrupt handling can only be enabled when the client instance is created in the main thread.

  • websocket_extra_options – Dictionary containing additional keyword arguments passed to aiohttp.ws_connect().

async connect(url, headers=None, transports=None, engineio_path='engine.io')

Connect to an Engine.IO server.

Parameters:
  • url – The URL of the Engine.IO server. It can include custom query string parameters if required by the server.

  • headers – A dictionary with custom headers to send with the connection request.

  • transports – The list of allowed transports. Valid transports are 'polling' and 'websocket'. If not given, the polling transport is connected first, then an upgrade to websocket is attempted.

  • engineio_path – The endpoint where the Engine.IO server is installed. The default value is appropriate for most cases.

Note: this method is a coroutine.

Example usage:

eio = engineio.Client()
await eio.connect('http://localhost:5000')
async wait()

Wait until the connection with the server ends.

Client applications can use this function to block the main thread during the life of the connection.

Note: this method is a coroutine.

async send(data)

Send a message to the server.

Parameters:

data – The data to send to the server. Data can be of type str, bytes, list or dict. If a list or dict, the data will be serialized as JSON.

Note: this method is a coroutine.

async disconnect(abort=False)

Disconnect from the server.

Parameters:

abort – If set to True, do not wait for background tasks associated with the connection to end.

Note: this method is a coroutine.

start_background_task(target, *args, **kwargs)

Start a background task.

This is a utility function that applications can use to start a background task.

Parameters:
  • target – the target function to execute.

  • args – arguments to pass to the function.

  • kwargs – keyword arguments to pass to the function.

The return value is a asyncio.Task object.

async sleep(seconds=0)

Sleep for the requested amount of time.

Note: this method is a coroutine.

create_queue()

Create a queue object.

create_event()

Create an event object.

on(event, handler=None)

Register an event handler.

Parameters:
  • event – The event name. Can be 'connect', 'message' or 'disconnect'.

  • handler – The function that should be invoked to handle the event. When this parameter is not given, the method acts as a decorator for the handler function.

Example usage:

# as a decorator:
@eio.on('connect')
def connect_handler():
    print('Connection request')

# as a method:
def message_handler(msg):
    print('Received message: ', msg)
    eio.send('response')
eio.on('message', message_handler)
transport()

Return the name of the transport currently in use.

The possible values returned by this function are 'polling' and 'websocket'.

class engineio.Server(async_mode=None, ping_interval=25, ping_timeout=20, max_http_buffer_size=1000000, allow_upgrades=True, http_compression=True, compression_threshold=1024, cookie=None, cors_allowed_origins=None, cors_credentials=True, logger=False, json=None, async_handlers=True, monitor_clients=None, transports=None, **kwargs)

An Engine.IO server.

This class implements a fully compliant Engine.IO web server with support for websocket and long-polling transports.

Parameters:
  • async_mode – The asynchronous model to use. See the Deployment section in the documentation for a description of the available options. Valid async modes are “threading”, “eventlet”, “gevent” and “gevent_uwsgi”. If this argument is not given, “eventlet” is tried first, then “gevent_uwsgi”, then “gevent”, and finally “threading”. The first async mode that has all its dependencies installed is the one that is chosen.

  • ping_interval – The interval in seconds at which the server pings the client. The default is 25 seconds. For advanced control, a two element tuple can be given, where the first number is the ping interval and the second is a grace period added by the server.

  • ping_timeout – The time in seconds that the client waits for the server to respond before disconnecting. The default is 20 seconds.

  • max_http_buffer_size – The maximum size that is accepted for incoming messages. The default is 1,000,000 bytes. In spite of its name, the value set in this argument is enforced for HTTP long-polling and WebSocket connections.

  • allow_upgrades – Whether to allow transport upgrades or not. The default is True.

  • http_compression – Whether to compress packages when using the polling transport. The default is True.

  • compression_threshold – Only compress messages when their byte size is greater than this value. The default is 1024 bytes.

  • cookie – If set to a string, it is the name of the HTTP cookie the server sends back tot he client containing the client session id. If set to a dictionary, the 'name' key contains the cookie name and other keys define cookie attributes, where the value of each attribute can be a string, a callable with no arguments, or a boolean. If set to None (the default), a cookie is not sent to the client.

  • cors_allowed_origins – Origin or list of origins that are allowed to connect to this server. Only the same origin is allowed by default. Set this argument to '*' to allow all origins, or to [] to disable CORS handling.

  • cors_credentials – Whether credentials (cookies, authentication) are allowed in requests to this server. The default is True.

  • logger – To enable logging set to True or pass a logger object to use. To disable logging set to False. The default is False. Note that fatal errors are logged even when logger is False.

  • json – An alternative json module to use for encoding and decoding packets. Custom json modules must have dumps and loads functions that are compatible with the standard library versions.

  • async_handlers – If set to True, run message event handlers in non-blocking threads. To run handlers synchronously, set to False. The default is True.

  • monitor_clients – If set to True, a background task will ensure inactive clients are closed. Set to False to disable the monitoring task (not recommended). The default is True.

  • transports – The list of allowed transports. Valid transports are 'polling' and 'websocket'. Defaults to ['polling', 'websocket'].

  • kwargs – Reserved for future extensions, any additional parameters given as keyword arguments will be silently ignored.

send(sid, data)

Send a message to a client.

Parameters:
  • sid – The session id of the recipient client.

  • data – The data to send to the client. Data can be of type str, bytes, list or dict. If a list or dict, the data will be serialized as JSON.

send_packet(sid, pkt)

Send a raw packet to a client.

Parameters:
  • sid – The session id of the recipient client.

  • pkt – The packet to send to the client.

get_session(sid)

Return the user session for a client.

Parameters:

sid – The session id of the client.

The return value is a dictionary. Modifications made to this dictionary are not guaranteed to be preserved unless save_session() is called, or when the session context manager is used.

save_session(sid, session)

Store the user session for a client.

Parameters:
  • sid – The session id of the client.

  • session – The session dictionary.

session(sid)

Return the user session for a client with context manager syntax.

Parameters:

sid – The session id of the client.

This is a context manager that returns the user session dictionary for the client. Any changes that are made to this dictionary inside the context manager block are saved back to the session. Example usage:

@eio.on('connect')
def on_connect(sid, environ):
    username = authenticate_user(environ)
    if not username:
        return False
    with eio.session(sid) as session:
        session['username'] = username

@eio.on('message')
def on_message(sid, msg):
    with eio.session(sid) as session:
        print('received message from ', session['username'])
disconnect(sid=None)

Disconnect a client.

Parameters:

sid – The session id of the client to close. If this parameter is not given, then all clients are closed.

handle_request(environ, start_response)

Handle an HTTP request from the client.

This is the entry point of the Engine.IO application, using the same interface as a WSGI application. For the typical usage, this function is invoked by the Middleware instance, but it can be invoked directly when the middleware is not used.

Parameters:
  • environ – The WSGI environment.

  • start_response – The WSGI start_response function.

This function returns the HTTP response body to deliver to the client as a byte sequence.

shutdown()

Stop Socket.IO background tasks.

This method stops background activity initiated by the Socket.IO server. It must be called before shutting down the web server.

start_background_task(target, *args, **kwargs)

Start a background task using the appropriate async model.

This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode.

Parameters:
  • target – the target function to execute.

  • args – arguments to pass to the function.

  • kwargs – keyword arguments to pass to the function.

This function returns an object that represents the background task, on which the join() methond can be invoked to wait for the task to complete.

sleep(seconds=0)

Sleep for the requested amount of time using the appropriate async model.

This is a utility function that applications can use to put a task to sleep without having to worry about using the correct call for the selected async mode.

create_event(*args, **kwargs)

Create an event object using the appropriate async model.

This is a utility function that applications can use to create an event without having to worry about using the correct call for the selected async mode.

create_queue(*args, **kwargs)

Create a queue object using the appropriate async model.

This is a utility function that applications can use to create a queue without having to worry about using the correct call for the selected async mode.

generate_id()

Generate a unique session id.

get_queue_empty_exception()

Return the queue empty exception for the appropriate async model.

This is a utility function that applications can use to work with a queue without having to worry about using the correct call for the selected async mode.

on(event, handler=None)

Register an event handler.

Parameters:
  • event – The event name. Can be 'connect', 'message' or 'disconnect'.

  • handler – The function that should be invoked to handle the event. When this parameter is not given, the method acts as a decorator for the handler function.

Example usage:

# as a decorator:
@eio.on('connect')
def connect_handler(sid, environ):
    print('Connection request')
    if environ['REMOTE_ADDR'] in blacklisted:
        return False  # reject

# as a method:
def message_handler(sid, msg):
    print('Received message: ', msg)
    eio.send(sid, 'response')
eio.on('message', message_handler)

The handler function receives the sid (session ID) for the client as first argument. The 'connect' event handler receives the WSGI environment as a second argument, and can return False to reject the connection. The 'message' handler receives the message payload as a second argument. The 'disconnect' handler does not take a second argument.

transport(sid)

Return the name of the transport used by the client.

The two possible values returned by this function are 'polling' and 'websocket'.

Parameters:

sid – The session of the client.

class engineio.AsyncServer(async_mode=None, ping_interval=25, ping_timeout=20, max_http_buffer_size=1000000, allow_upgrades=True, http_compression=True, compression_threshold=1024, cookie=None, cors_allowed_origins=None, cors_credentials=True, logger=False, json=None, async_handlers=True, monitor_clients=None, transports=None, **kwargs)

An Engine.IO server for asyncio.

This class implements a fully compliant Engine.IO web server with support for websocket and long-polling transports, compatible with the asyncio framework on Python 3.5 or newer.

Parameters:
  • async_mode – The asynchronous model to use. See the Deployment section in the documentation for a description of the available options. Valid async modes are “aiohttp”, “sanic”, “tornado” and “asgi”. If this argument is not given, “aiohttp” is tried first, followed by “sanic”, “tornado”, and finally “asgi”. The first async mode that has all its dependencies installed is the one that is chosen.

  • ping_interval – The interval in seconds at which the server pings the client. The default is 25 seconds. For advanced control, a two element tuple can be given, where the first number is the ping interval and the second is a grace period added by the server.

  • ping_timeout – The time in seconds that the client waits for the server to respond before disconnecting. The default is 20 seconds.

  • max_http_buffer_size – The maximum size that is accepted for incoming messages. The default is 1,000,000 bytes. In spite of its name, the value set in this argument is enforced for HTTP long-polling and WebSocket connections.

  • allow_upgrades – Whether to allow transport upgrades or not.

  • http_compression – Whether to compress packages when using the polling transport.

  • compression_threshold – Only compress messages when their byte size is greater than this value.

  • cookie – If set to a string, it is the name of the HTTP cookie the server sends back tot he client containing the client session id. If set to a dictionary, the 'name' key contains the cookie name and other keys define cookie attributes, where the value of each attribute can be a string, a callable with no arguments, or a boolean. If set to None (the default), a cookie is not sent to the client.

  • cors_allowed_origins – Origin or list of origins that are allowed to connect to this server. Only the same origin is allowed by default. Set this argument to '*' to allow all origins, or to [] to disable CORS handling.

  • cors_credentials – Whether credentials (cookies, authentication) are allowed in requests to this server.

  • logger – To enable logging set to True or pass a logger object to use. To disable logging set to False. Note that fatal errors are logged even when logger is False.

  • json – An alternative json module to use for encoding and decoding packets. Custom json modules must have dumps and loads functions that are compatible with the standard library versions.

  • async_handlers – If set to True, run message event handlers in non-blocking threads. To run handlers synchronously, set to False. The default is True.

  • transports – The list of allowed transports. Valid transports are 'polling' and 'websocket'. Defaults to ['polling', 'websocket'].

  • kwargs – Reserved for future extensions, any additional parameters given as keyword arguments will be silently ignored.

attach(app, engineio_path='engine.io')

Attach the Engine.IO server to an application.

async send(sid, data)

Send a message to a client.

Parameters:
  • sid – The session id of the recipient client.

  • data – The data to send to the client. Data can be of type str, bytes, list or dict. If a list or dict, the data will be serialized as JSON.

Note: this method is a coroutine.

async send_packet(sid, pkt)

Send a raw packet to a client.

Parameters:
  • sid – The session id of the recipient client.

  • pkt – The packet to send to the client.

Note: this method is a coroutine.

async get_session(sid)

Return the user session for a client.

Parameters:

sid – The session id of the client.

The return value is a dictionary. Modifications made to this dictionary are not guaranteed to be preserved. If you want to modify the user session, use the session context manager instead.

async save_session(sid, session)

Store the user session for a client.

Parameters:
  • sid – The session id of the client.

  • session – The session dictionary.

session(sid)

Return the user session for a client with context manager syntax.

Parameters:

sid – The session id of the client.

This is a context manager that returns the user session dictionary for the client. Any changes that are made to this dictionary inside the context manager block are saved back to the session. Example usage:

@eio.on('connect')
def on_connect(sid, environ):
    username = authenticate_user(environ)
    if not username:
        return False
    with eio.session(sid) as session:
        session['username'] = username

@eio.on('message')
def on_message(sid, msg):
    async with eio.session(sid) as session:
        print('received message from ', session['username'])
async disconnect(sid=None)

Disconnect a client.

Parameters:

sid – The session id of the client to close. If this parameter is not given, then all clients are closed.

Note: this method is a coroutine.

async handle_request(*args, **kwargs)

Handle an HTTP request from the client.

This is the entry point of the Engine.IO application. This function returns the HTTP response to deliver to the client.

Note: this method is a coroutine.

async shutdown()

Stop Socket.IO background tasks.

This method stops background activity initiated by the Socket.IO server. It must be called before shutting down the web server.

start_background_task(target, *args, **kwargs)

Start a background task using the appropriate async model.

This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode.

Parameters:
  • target – the target function to execute.

  • args – arguments to pass to the function.

  • kwargs – keyword arguments to pass to the function.

The return value is a asyncio.Task object.

async sleep(seconds=0)

Sleep for the requested amount of time using the appropriate async model.

This is a utility function that applications can use to put a task to sleep without having to worry about using the correct call for the selected async mode.

Note: this method is a coroutine.

create_queue(*args, **kwargs)

Create a queue object using the appropriate async model.

This is a utility function that applications can use to create a queue without having to worry about using the correct call for the selected async mode. For asyncio based async modes, this returns an instance of asyncio.Queue.

get_queue_empty_exception()

Return the queue empty exception for the appropriate async model.

This is a utility function that applications can use to work with a queue without having to worry about using the correct call for the selected async mode. For asyncio based async modes, this returns an instance of asyncio.QueueEmpty.

create_event(*args, **kwargs)

Create an event object using the appropriate async model.

This is a utility function that applications can use to create an event without having to worry about using the correct call for the selected async mode. For asyncio based async modes, this returns an instance of asyncio.Event.

generate_id()

Generate a unique session id.

on(event, handler=None)

Register an event handler.

Parameters:
  • event – The event name. Can be 'connect', 'message' or 'disconnect'.

  • handler – The function that should be invoked to handle the event. When this parameter is not given, the method acts as a decorator for the handler function.

Example usage:

# as a decorator:
@eio.on('connect')
def connect_handler(sid, environ):
    print('Connection request')
    if environ['REMOTE_ADDR'] in blacklisted:
        return False  # reject

# as a method:
def message_handler(sid, msg):
    print('Received message: ', msg)
    eio.send(sid, 'response')
eio.on('message', message_handler)

The handler function receives the sid (session ID) for the client as first argument. The 'connect' event handler receives the WSGI environment as a second argument, and can return False to reject the connection. The 'message' handler receives the message payload as a second argument. The 'disconnect' handler does not take a second argument.

transport(sid)

Return the name of the transport used by the client.

The two possible values returned by this function are 'polling' and 'websocket'.

Parameters:

sid – The session of the client.

class engineio.WSGIApp(engineio_app, wsgi_app=None, static_files=None, engineio_path='engine.io')

WSGI application middleware for Engine.IO.

This middleware dispatches traffic to an Engine.IO application. It can also serve a list of static files to the client, or forward unrelated HTTP traffic to another WSGI application.

Parameters:
  • engineio_app – The Engine.IO server. Must be an instance of the engineio.Server class.

  • wsgi_app – The WSGI app that receives all other traffic.

  • static_files – A dictionary with static file mapping rules. See the documentation for details on this argument.

  • engineio_path – The endpoint where the Engine.IO application should be installed. The default value is appropriate for most cases.

Example usage:

import engineio
import eventlet

eio = engineio.Server()
app = engineio.WSGIApp(eio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'},
    '/index.html': {'content_type': 'text/html',
                    'filename': 'index.html'},
})
eventlet.wsgi.server(eventlet.listen(('', 8000)), app)
class engineio.ASGIApp(engineio_server, other_asgi_app=None, static_files=None, engineio_path='engine.io', on_startup=None, on_shutdown=None)

ASGI application middleware for Engine.IO.

This middleware dispatches traffic to an Engine.IO application. It can also serve a list of static files to the client, or forward unrelated HTTP traffic to another ASGI application.

Parameters:
  • engineio_server – The Engine.IO server. Must be an instance of the engineio.AsyncServer class.

  • static_files – A dictionary with static file mapping rules. See the documentation for details on this argument.

  • other_asgi_app – A separate ASGI app that receives all other traffic.

  • engineio_path – The endpoint where the Engine.IO application should be installed. The default value is appropriate for most cases. With a value of None, all incoming traffic is directed to the Engine.IO server, with the assumption that routing, if necessary, is handled by a different layer. When this option is set to None, static_files and other_asgi_app are ignored.

  • on_startup – function to be called on application startup; can be coroutine

  • on_shutdown – function to be called on application shutdown; can be coroutine

Example usage:

import engineio
import uvicorn

eio = engineio.AsyncServer()
app = engineio.ASGIApp(eio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'},
    '/index.html': {'content_type': 'text/html',
                    'filename': 'index.html'},
})
uvicorn.run(app, '127.0.0.1', 5000)
async not_found(receive, send)

Return a 404 Not Found error to the client.

class engineio.Middleware(engineio_app, wsgi_app=None, engineio_path='engine.io')

This class has been renamed to WSGIApp and is now deprecated.