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 '*' or ['*'] 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. This is a process-wide setting, all instantiated servers and clients must use the same JSON module.

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

class reason

Disconnection reasons.

CLIENT_DISCONNECT = 'client disconnect'

Client-initiated disconnection.

PING_TIMEOUT = 'ping timeout'

Ping timeout.

SERVER_DISCONNECT = 'server disconnect'

Server-initiated disconnection.

TRANSPORT_CLOSE = 'transport close'

Transport close.

TRANSPORT_ERROR = 'transport error'

Transport error.

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.