API Reference

Client class

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')
create_event(*args, **kwargs)

Create an event object.

create_queue(*args, **kwargs)

Create a queue object.

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.
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)
send(data)

Send a message to a client.

Parameters: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.
sleep(seconds=0)

Sleep for the requested amount of time.

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.

transport()

Return the name of the transport currently in use.

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

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.

AsyncClient class

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().
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')
create_event()

Create an event object.

create_queue()

Create a queue object.

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.

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)
send(data)

Send a message to a client.

Parameters: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.

sleep(seconds=0)

Sleep for the requested amount of time.

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.

transport()

Return the name of the transport currently in use.

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

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.

Server class

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 of a message when using the polling transport. The default is 1,000,000 bytes.
  • 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.
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.

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.
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.

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.

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.

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.

save_session(sid, session)

Store the user session for a client.

Parameters:
  • sid – The session id of the client.
  • session – The session dictionary.
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.
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'])
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.

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.

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.

AsyncServer class

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 of a message when using the polling transport. The default is 1,000,000 bytes.
  • 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.

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.

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.

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.

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. For asyncio based async modes, this returns an instance of asyncio.QueueEmpty.

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.

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.

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.

save_session(sid, session)

Store the user session for a client.

Parameters:
  • sid – The session id of the client.
  • session – The session dictionary.
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.

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'])
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.

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.

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.

WSGIApp class

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)

ASGIApp class

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.
  • 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)

Middleware class (deprecated)

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

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