API Reference

Client class

class socketio.Client(reconnection=True, reconnection_attempts=0, reconnection_delay=1, reconnection_delay_max=5, randomization_factor=0.5, logger=False, binary=False, json=None, **kwargs)

A Socket.IO client.

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

Parameters:
  • reconnectionTrue if the client should automatically attempt to reconnect to the server after an interruption, or False to not reconnect. The default is True.

  • reconnection_attempts – How many reconnection attempts to issue before giving up, or 0 for infinity attempts. The default is 0.

  • reconnection_delay – How long to wait in seconds before the first reconnection attempt. Each successive attempt doubles this delay.

  • reconnection_delay_max – The maximum delay between reconnection attempts.

  • randomization_factor – Randomization amount for each delay between reconnection attempts. The default is 0.5, which means that each delay is randomly adjusted by +/- 50%.

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

  • binaryTrue to support binary payloads, False to treat all payloads as text. On Python 2, if this is set to True, unicode values are treated as text, and str and bytes values are treated as binary. This option has no effect on Python 3, where text and binary payloads are always automatically discovered.

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

The Engine.IO configuration supports the following settings:

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

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

  • engineio_logger – To enable Engine.IO 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 engineio_logger is False.

call(event, data=None, namespace=None, timeout=60)

Emit a custom event to a client and wait for the response.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

  • data – The data to send to the server. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • timeout – The waiting timeout. If the timeout is reached before the client acknowledges the event, then a TimeoutError exception is raised.

Note: this method is not thread safe. If multiple threads are emitting at the same time on the same client connection, messages composed of multiple packets may end up being sent in an incorrect sequence. Use standard concurrency solutions (such as a Lock object) to prevent this situation.

connect(url, headers={}, transports=None, namespaces=None, socketio_path='socket.io')

Connect to a Socket.IO server.

Parameters:
  • url – The URL of the Socket.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.

  • namespaces – The list of custom namespaces to connect, in addition to the default namespace. If not given, the namespace list is obtained from the registered event handlers.

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

Example usage:

sio = socketio.Client()
sio.connect('http://localhost:5000')
disconnect()

Disconnect from the server.

emit(event, data=None, namespace=None, callback=None)

Emit a custom event to one or more connected clients.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

  • data – The data to send to the server. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • callback – If given, this function will be called to acknowledge the the server has received the message. The arguments that will be passed to the function are those provided by the server.

Note: this method is not thread safe. If multiple threads are emitting at the same time on the same client connection, messages composed of multiple packets may end up being sent in an incorrect sequence. Use standard concurrency solutions (such as a Lock object) to prevent this situation.

event(*args, **kwargs)

Decorator to register an event handler.

This is a simplified version of the on() method that takes the event name from the decorated function.

Example usage:

@sio.event
def my_event(data):
    print('Received data: ', data)

The above example is equivalent to:

@sio.on('my_event')
def my_event(data):
    print('Received data: ', data)

A custom namespace can be given as an argument to the decorator:

@sio.event(namespace='/test')
def my_event(data):
    print('Received data: ', data)
on(event, handler=None, namespace=None)

Register an event handler.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

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

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the handler is associated with the default namespace.

Example usage:

# as a decorator:
@sio.on('connect')
def connect_handler():
    print('Connected!')

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

The 'connect' event handler receives no arguments. The 'message' handler and handlers for custom event names receive the message payload as only argument. Any values returned from a message handler will be passed to the client’s acknowledgement callback function if it exists. The 'disconnect' handler does not take arguments.

register_namespace(namespace_handler)

Register a namespace handler object.

Parameters:

namespace_handler – An instance of a Namespace subclass that handles all the event traffic for a namespace.

send(data, namespace=None, callback=None)

Send a message to one or more connected clients.

This function emits an event with the name 'message'. Use emit() to issue custom event names.

Parameters:
  • data – The data to send to the server. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • callback – If given, this function will be called to acknowledge the the server has received the message. The arguments that will be passed to the function are those provided by the server.

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 compatible with the Thread class in the Python standard library. The start() method on this object is already called by this function.

transport()

Return the name of the transport used by the client.

The two 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 socketio.AsyncClient(reconnection=True, reconnection_attempts=0, reconnection_delay=1, reconnection_delay_max=5, randomization_factor=0.5, logger=False, binary=False, json=None, **kwargs)

A Socket.IO client for asyncio.

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

Parameters:
  • reconnectionTrue if the client should automatically attempt to reconnect to the server after an interruption, or False to not reconnect. The default is True.

  • reconnection_attempts – How many reconnection attempts to issue before giving up, or 0 for infinity attempts. The default is 0.

  • reconnection_delay – How long to wait in seconds before the first reconnection attempt. Each successive attempt doubles this delay.

  • reconnection_delay_max – The maximum delay between reconnection attempts.

  • randomization_factor – Randomization amount for each delay between reconnection attempts. The default is 0.5, which means that each delay is randomly adjusted by +/- 50%.

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

  • binaryTrue to support binary payloads, False to treat all payloads as text. On Python 2, if this is set to True, unicode values are treated as text, and str and bytes values are treated as binary. This option has no effect on Python 3, where text and binary payloads are always automatically discovered.

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

The Engine.IO configuration supports the following settings:

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

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

  • engineio_logger – To enable Engine.IO 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 engineio_logger is False.

async call(event, data=None, namespace=None, timeout=60)

Emit a custom event to a client and wait for the response.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

  • data – The data to send to the server. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • timeout – The waiting timeout. If the timeout is reached before the client acknowledges the event, then a TimeoutError exception is raised.

Note: this method is not designed to be used concurrently. If multiple tasks are emitting at the same time on the same client connection, then messages composed of multiple packets may end up being sent in an incorrect sequence. Use standard concurrency solutions (such as a Lock object) to prevent this situation.

Note 2: this method is a coroutine.

async connect(url, headers={}, transports=None, namespaces=None, socketio_path='socket.io')

Connect to a Socket.IO server.

Parameters:
  • url – The URL of the Socket.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.

  • namespaces – The list of custom namespaces to connect, in addition to the default namespace. If not given, the namespace list is obtained from the registered event handlers.

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

Note: this method is a coroutine.

Example usage:

sio = socketio.AsyncClient()
sio.connect('http://localhost:5000')
async disconnect()

Disconnect from the server.

Note: this method is a coroutine.

async emit(event, data=None, namespace=None, callback=None)

Emit a custom event to one or more connected clients.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

  • data – The data to send to the server. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • callback – If given, this function will be called to acknowledge the the server has received the message. The arguments that will be passed to the function are those provided by the server.

Note: this method is not designed to be used concurrently. If multiple tasks are emitting at the same time on the same client connection, then messages composed of multiple packets may end up being sent in an incorrect sequence. Use standard concurrency solutions (such as a Lock object) to prevent this situation.

Note 2: this method is a coroutine.

event(*args, **kwargs)

Decorator to register an event handler.

This is a simplified version of the on() method that takes the event name from the decorated function.

Example usage:

@sio.event
def my_event(data):
    print('Received data: ', data)

The above example is equivalent to:

@sio.on('my_event')
def my_event(data):
    print('Received data: ', data)

A custom namespace can be given as an argument to the decorator:

@sio.event(namespace='/test')
def my_event(data):
    print('Received data: ', data)
on(event, handler=None, namespace=None)

Register an event handler.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

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

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the handler is associated with the default namespace.

Example usage:

# as a decorator:
@sio.on('connect')
def connect_handler():
    print('Connected!')

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

The 'connect' event handler receives no arguments. The 'message' handler and handlers for custom event names receive the message payload as only argument. Any values returned from a message handler will be passed to the client’s acknowledgement callback function if it exists. The 'disconnect' handler does not take arguments.

register_namespace(namespace_handler)

Register a namespace handler object.

Parameters:

namespace_handler – An instance of a Namespace subclass that handles all the event traffic for a namespace.

async send(data, namespace=None, callback=None)

Send a message to one or more connected clients.

This function emits an event with the name 'message'. Use emit() to issue custom event names.

Parameters:
  • data – The data to send to the server. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • callback – If given, this function will be called to acknowledge the the server has received the message. The arguments that will be passed to the function are those provided by the server.

Note: this method is a coroutine.

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.

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 compatible with the Thread class in the Python standard library. The start() method on this object is already called by this function.

transport()

Return the name of the transport used by the client.

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

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.

Server class

class socketio.Server(client_manager=None, logger=False, binary=False, json=None, async_handlers=True, always_connect=False, **kwargs)

A Socket.IO server.

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

Parameters:
  • client_manager – The client manager instance that will manage the client list. When this is omitted, the client list is stored in an in-memory structure, so the use of multiple connected servers is not possible.

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

  • binaryTrue to support binary payloads, False to treat all payloads as text. On Python 2, if this is set to True, unicode values are treated as text, and str and bytes values are treated as binary. This option has no effect on Python 3, where text and binary payloads are always automatically discovered.

  • 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, event handlers for a client are executed in separate threads. To run handlers for a client synchronously, set to False. The default is True.

  • always_connect – When set to False, new connections are provisory until the connect handler returns something other than False, at which point they are accepted. When set to True, connections are immediately accepted, and then if the connect handler returns False a disconnect is issued. Set to True if you need to emit events from the connect handler and your client is confused when it receives events before the connection acceptance. In any other case use the default of False.

  • kwargs – Connection parameters for the underlying Engine.IO server.

The Engine.IO configuration supports the following settings:

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 then one that is chosen.

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

  • ping_interval – The interval in seconds at which the client pings the server. The default is 25 seconds.

  • max_http_buffer_size – The maximum size of a message when using the polling transport. The default is 100,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 – Name of the HTTP cookie that contains the client session id. If set to None, a cookie is not sent to the client. The default is 'io'.

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

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

  • engineio_logger – To enable Engine.IO 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 engineio_logger is False.

call(event, data=None, to=None, sid=None, namespace=None, timeout=60, **kwargs)

Emit a custom event to a client and wait for the response.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

  • data – The data to send to the client or clients. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • to – The session ID of the recipient client.

  • sid – Alias for the to parameter.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • timeout – The waiting timeout. If the timeout is reached before the client acknowledges the event, then a TimeoutError exception is raised.

  • ignore_queue – Only used when a message queue is configured. If set to True, the event is emitted to the client directly, without going through the queue. This is more efficient, but only works when a single server process is used. It is recommended to always leave this parameter with its default value of False.

Note: this method is not thread safe. If multiple threads are emitting at the same time to the same client, then messages composed of multiple packets may end up being sent in an incorrect sequence. Use standard concurrency solutions (such as a Lock object) to prevent this situation.

close_room(room, namespace=None)

Close a room.

This function removes all the clients from the given room.

Parameters:
  • room – Room name.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the default namespace is used.

disconnect(sid, namespace=None, ignore_queue=False)

Disconnect a client.

Parameters:
  • sid – Session ID of the client.

  • namespace – The Socket.IO namespace to disconnect. If this argument is omitted the default namespace is used.

  • ignore_queue – Only used when a message queue is configured. If set to True, the disconnect is processed locally, without broadcasting on the queue. It is recommended to always leave this parameter with its default value of False.

emit(event, data=None, to=None, room=None, skip_sid=None, namespace=None, callback=None, **kwargs)

Emit a custom event to one or more connected clients.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

  • data – The data to send to the client or clients. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • to – The recipient of the message. This can be set to the session ID of a client to address only that client, or to to any custom room created by the application to address all the clients in that room, If this argument is omitted the event is broadcasted to all connected clients.

  • room – Alias for the to parameter.

  • skip_sid – The session ID of a client to skip when broadcasting to a room or to all clients. This can be used to prevent a message from being sent to the sender. To skip multiple sids, pass a list.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • callback – If given, this function will be called to acknowledge the the client has received the message. The arguments that will be passed to the function are those provided by the client. Callback functions can only be used when addressing an individual client.

  • ignore_queue – Only used when a message queue is configured. If set to True, the event is emitted to the clients directly, without going through the queue. This is more efficient, but only works when a single server process is used. It is recommended to always leave this parameter with its default value of False.

Note: this method is not thread safe. If multiple threads are emitting at the same time to the same client, then messages composed of multiple packets may end up being sent in an incorrect sequence. Use standard concurrency solutions (such as a Lock object) to prevent this situation.

enter_room(sid, room, namespace=None)

Enter a room.

This function adds the client to a room. The emit() and send() functions can optionally broadcast events to all the clients in a room.

Parameters:
  • sid – Session ID of the client.

  • room – Room name. If the room does not exist it is created.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the default namespace is used.

event(*args, **kwargs)

Decorator to register an event handler.

This is a simplified version of the on() method that takes the event name from the decorated function.

Example usage:

@sio.event
def my_event(data):
    print('Received data: ', data)

The above example is equivalent to:

@sio.on('my_event')
def my_event(data):
    print('Received data: ', data)

A custom namespace can be given as an argument to the decorator:

@sio.event(namespace='/test')
def my_event(data):
    print('Received data: ', data)
get_session(sid, namespace=None)

Return the user session for a client.

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

  • namespace – The Socket.IO namespace. If this argument is omitted the default namespace is used.

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

leave_room(sid, room, namespace=None)

Leave a room.

This function removes the client from a room.

Parameters:
  • sid – Session ID of the client.

  • room – Room name.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the default namespace is used.

on(event, handler=None, namespace=None)

Register an event handler.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

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

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the handler is associated with the default namespace.

Example usage:

# as a decorator:
@socket_io.on('connect', namespace='/chat')
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')
socket_io.on('message', namespace='/chat', handler=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 and handlers for custom event names receive the message payload as a second argument. Any values returned from a message handler will be passed to the client’s acknowledgement callback function if it exists. The 'disconnect' handler does not take a second argument.

register_namespace(namespace_handler)

Register a namespace handler object.

Parameters:

namespace_handler – An instance of a Namespace subclass that handles all the event traffic for a namespace.

rooms(sid, namespace=None)

Return the rooms a client is in.

Parameters:
  • sid – Session ID of the client.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the default namespace is used.

save_session(sid, session, namespace=None)

Store the user session for a client.

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

  • session – The session dictionary.

  • namespace – The Socket.IO namespace. If this argument is omitted the default namespace is used.

send(data, to=None, room=None, skip_sid=None, namespace=None, callback=None, **kwargs)

Send a message to one or more connected clients.

This function emits an event with the name 'message'. Use emit() to issue custom event names.

Parameters:
  • data – The data to send to the client or clients. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • to – The recipient of the message. This can be set to the session ID of a client to address only that client, or to to any custom room created by the application to address all the clients in that room, If this argument is omitted the event is broadcasted to all connected clients.

  • room – Alias for the to parameter.

  • skip_sid – The session ID of a client to skip when broadcasting to a room or to all clients. This can be used to prevent a message from being sent to the sender. To skip multiple sids, pass a list.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • callback – If given, this function will be called to acknowledge the the client has received the message. The arguments that will be passed to the function are those provided by the client. Callback functions can only be used when addressing an individual client.

  • ignore_queue – Only used when a message queue is configured. If set to True, the event is emitted to the clients directly, without going through the queue. This is more efficient, but only works when a single server process is used. It is recommended to always leave this parameter with its default value of False.

session(sid, namespace=None)

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:

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

@sio.on('message')
def on_message(sid, msg):
    with sio.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 compatible with the Thread class in the Python standard library. The start() method on this object is already called by this function.

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 socketio.AsyncServer(client_manager=None, logger=False, json=None, async_handlers=True, **kwargs)

A Socket.IO server for asyncio.

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

Parameters:
  • client_manager – The client manager instance that will manage the client list. When this is omitted, the client list is stored in an in-memory structure, so the use of multiple connected servers is not possible.

  • 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, event handlers are executed in separate threads. To run handlers synchronously, set to False. The default is True.

  • kwargs – Connection parameters for the underlying Engine.IO server.

The Engine.IO configuration supports the following settings:

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”. If this argument is not given, an async mode is chosen based on the installed packages.

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

  • ping_interval – The interval in seconds at which the client pings the server.

  • max_http_buffer_size – The maximum size of a message when using the polling transport.

  • 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 – Name of the HTTP cookie that contains the client session id. If set to None, 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.

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

  • engineio_logger – To enable Engine.IO 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 engineio_logger is False.

attach(app, socketio_path='socket.io')

Attach the Socket.IO server to an application.

async call(event, data=None, to=None, sid=None, namespace=None, timeout=60, **kwargs)

Emit a custom event to a client and wait for the response.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

  • data – The data to send to the client or clients. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • to – The session ID of the recipient client.

  • sid – Alias for the to parameter.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • timeout – The waiting timeout. If the timeout is reached before the client acknowledges the event, then a TimeoutError exception is raised.

  • ignore_queue – Only used when a message queue is configured. If set to True, the event is emitted to the client directly, without going through the queue. This is more efficient, but only works when a single server process is used. It is recommended to always leave this parameter with its default value of False.

Note: this method is not designed to be used concurrently. If multiple tasks are emitting at the same time to the same client connection, then messages composed of multiple packets may end up being sent in an incorrect sequence. Use standard concurrency solutions (such as a Lock object) to prevent this situation.

Note 2: this method is a coroutine.

async close_room(room, namespace=None)

Close a room.

This function removes all the clients from the given room.

Parameters:
  • room – Room name.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the default namespace is used.

Note: this method is a coroutine.

async disconnect(sid, namespace=None, ignore_queue=False)

Disconnect a client.

Parameters:
  • sid – Session ID of the client.

  • namespace – The Socket.IO namespace to disconnect. If this argument is omitted the default namespace is used.

  • ignore_queue – Only used when a message queue is configured. If set to True, the disconnect is processed locally, without broadcasting on the queue. It is recommended to always leave this parameter with its default value of False.

Note: this method is a coroutine.

async emit(event, data=None, to=None, room=None, skip_sid=None, namespace=None, callback=None, **kwargs)

Emit a custom event to one or more connected clients.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

  • data – The data to send to the client or clients. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • to – The recipient of the message. This can be set to the session ID of a client to address only that client, or to to any custom room created by the application to address all the clients in that room, If this argument is omitted the event is broadcasted to all connected clients.

  • room – Alias for the to parameter.

  • skip_sid – The session ID of a client to skip when broadcasting to a room or to all clients. This can be used to prevent a message from being sent to the sender.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • callback – If given, this function will be called to acknowledge the the client has received the message. The arguments that will be passed to the function are those provided by the client. Callback functions can only be used when addressing an individual client.

  • ignore_queue – Only used when a message queue is configured. If set to True, the event is emitted to the clients directly, without going through the queue. This is more efficient, but only works when a single server process is used. It is recommended to always leave this parameter with its default value of False.

Note: this method is not designed to be used concurrently. If multiple tasks are emitting at the same time to the same client connection, then messages composed of multiple packets may end up being sent in an incorrect sequence. Use standard concurrency solutions (such as a Lock object) to prevent this situation.

Note 2: this method is a coroutine.

enter_room(sid, room, namespace=None)

Enter a room.

This function adds the client to a room. The emit() and send() functions can optionally broadcast events to all the clients in a room.

Parameters:
  • sid – Session ID of the client.

  • room – Room name. If the room does not exist it is created.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the default namespace is used.

event(*args, **kwargs)

Decorator to register an event handler.

This is a simplified version of the on() method that takes the event name from the decorated function.

Example usage:

@sio.event
def my_event(data):
    print('Received data: ', data)

The above example is equivalent to:

@sio.on('my_event')
def my_event(data):
    print('Received data: ', data)

A custom namespace can be given as an argument to the decorator:

@sio.event(namespace='/test')
def my_event(data):
    print('Received data: ', data)
async get_session(sid, namespace=None)

Return the user session for a client.

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

  • namespace – The Socket.IO namespace. If this argument is omitted the default namespace is used.

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

Handle an HTTP request from the client.

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

Note: this method is a coroutine.

leave_room(sid, room, namespace=None)

Leave a room.

This function removes the client from a room.

Parameters:
  • sid – Session ID of the client.

  • room – Room name.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the default namespace is used.

on(event, handler=None, namespace=None)

Register an event handler.

Parameters:
  • event – The event name. It can be any string. The event names 'connect', 'message' and 'disconnect' are reserved and should not be used.

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

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the handler is associated with the default namespace.

Example usage:

# as a decorator:
@socket_io.on('connect', namespace='/chat')
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')
socket_io.on('message', namespace='/chat', handler=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 and handlers for custom event names receive the message payload as a second argument. Any values returned from a message handler will be passed to the client’s acknowledgement callback function if it exists. The 'disconnect' handler does not take a second argument.

register_namespace(namespace_handler)

Register a namespace handler object.

Parameters:

namespace_handler – An instance of a Namespace subclass that handles all the event traffic for a namespace.

rooms(sid, namespace=None)

Return the rooms a client is in.

Parameters:
  • sid – Session ID of the client.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the default namespace is used.

async save_session(sid, session, namespace=None)

Store the user session for a client.

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

  • session – The session dictionary.

  • namespace – The Socket.IO namespace. If this argument is omitted the default namespace is used.

async send(data, to=None, room=None, skip_sid=None, namespace=None, callback=None, **kwargs)

Send a message to one or more connected clients.

This function emits an event with the name 'message'. Use emit() to issue custom event names.

Parameters:
  • data – The data to send to the client or clients. Data can be of type str, bytes, list or dict. To send multiple arguments, use a tuple where each element is of one of the types indicated above.

  • to – The recipient of the message. This can be set to the session ID of a client to address only that client, or to to any custom room created by the application to address all the clients in that room, If this argument is omitted the event is broadcasted to all connected clients.

  • room – Alias for the to parameter.

  • skip_sid – The session ID of a client to skip when broadcasting to a room or to all clients. This can be used to prevent a message from being sent to the sender.

  • namespace – The Socket.IO namespace for the event. If this argument is omitted the event is emitted to the default namespace.

  • callback – If given, this function will be called to acknowledge the the client has received the message. The arguments that will be passed to the function are those provided by the client. Callback functions can only be used when addressing an individual client.

  • ignore_queue – Only used when a message queue is configured. If set to True, the event is emitted to the clients directly, without going through the queue. This is more efficient, but only works when a single server process is used. It is recommended to always leave this parameter with its default value of False.

Note: this method is a coroutine.

session(sid, namespace=None)

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 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. Must be a coroutine.

  • args – arguments to pass to the function.

  • kwargs – keyword arguments to pass to the function.

The return value is a asyncio.Task object.

Note: this method is a coroutine.

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.

ConnectionRefusedError class

WSGIApp class

class socketio.WSGIApp(socketio_app, wsgi_app=None, static_files=None, socketio_path='socket.io')

WSGI middleware for Socket.IO.

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

Parameters:
  • socketio_app – The Socket.IO server. Must be an instance of the socketio.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.

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

Example usage:

import socketio
import eventlet
from . import wsgi_app

sio = socketio.Server()
app = socketio.WSGIApp(sio, wsgi_app)
eventlet.wsgi.server(eventlet.listen(('', 8000)), app)

ASGIApp class

class socketio.ASGIApp(socketio_server, other_asgi_app=None, static_files=None, socketio_path='socket.io', on_startup=None, on_shutdown=None)

ASGI application middleware for Socket.IO.

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

Parameters:
  • socketio_server – The Socket.IO server. Must be an instance of the socketio.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.

  • socketio_path – The endpoint where the Socket.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 socketio
import uvicorn

sio = socketio.AsyncServer()
app = engineio.ASGIApp(sio, static_files={
    '/': 'index.html',
    '/static': './public',
})
uvicorn.run(app, host='127.0.0.1', port=5000)

Middleware class (deprecated)

class socketio.Middleware(socketio_app, wsgi_app=None, socketio_path='socket.io')

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

ClientNamespace class

class socketio.ClientNamespace(namespace=None)

Base class for client-side class-based namespaces.

A class-based namespace is a class that contains all the event handlers for a Socket.IO namespace. The event handlers are methods of the class with the prefix on_, such as on_connect, on_disconnect, on_message, on_json, and so on.

Parameters:

namespace – The Socket.IO namespace to be used with all the event handlers defined in this class. If this argument is omitted, the default namespace is used.

disconnect()

Disconnect from the server.

The only difference with the socketio.Client.disconnect() method is that when the namespace argument is not given the namespace associated with the class is used.

emit(event, data=None, namespace=None, callback=None)

Emit a custom event to the server.

The only difference with the socketio.Client.emit() method is that when the namespace argument is not given the namespace associated with the class is used.

send(data, room=None, skip_sid=None, namespace=None, callback=None)

Send a message to the server.

The only difference with the socketio.Client.send() method is that when the namespace argument is not given the namespace associated with the class is used.

trigger_event(event, *args)

Dispatch an event to the proper handler method.

In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed, or if having a single method that catches all events is desired.

Namespace class

class socketio.Namespace(namespace=None)

Base class for server-side class-based namespaces.

A class-based namespace is a class that contains all the event handlers for a Socket.IO namespace. The event handlers are methods of the class with the prefix on_, such as on_connect, on_disconnect, on_message, on_json, and so on.

Parameters:

namespace – The Socket.IO namespace to be used with all the event handlers defined in this class. If this argument is omitted, the default namespace is used.

close_room(room, namespace=None)

Close a room.

The only difference with the socketio.Server.close_room() method is that when the namespace argument is not given the namespace associated with the class is used.

disconnect(sid, namespace=None)

Disconnect a client.

The only difference with the socketio.Server.disconnect() method is that when the namespace argument is not given the namespace associated with the class is used.

emit(event, data=None, room=None, skip_sid=None, namespace=None, callback=None)

Emit a custom event to one or more connected clients.

The only difference with the socketio.Server.emit() method is that when the namespace argument is not given the namespace associated with the class is used.

enter_room(sid, room, namespace=None)

Enter a room.

The only difference with the socketio.Server.enter_room() method is that when the namespace argument is not given the namespace associated with the class is used.

get_session(sid, namespace=None)

Return the user session for a client.

The only difference with the socketio.Server.get_session() method is that when the namespace argument is not given the namespace associated with the class is used.

leave_room(sid, room, namespace=None)

Leave a room.

The only difference with the socketio.Server.leave_room() method is that when the namespace argument is not given the namespace associated with the class is used.

rooms(sid, namespace=None)

Return the rooms a client is in.

The only difference with the socketio.Server.rooms() method is that when the namespace argument is not given the namespace associated with the class is used.

save_session(sid, session, namespace=None)

Store the user session for a client.

The only difference with the socketio.Server.save_session() method is that when the namespace argument is not given the namespace associated with the class is used.

send(data, room=None, skip_sid=None, namespace=None, callback=None)

Send a message to one or more connected clients.

The only difference with the socketio.Server.send() method is that when the namespace argument is not given the namespace associated with the class is used.

session(sid, namespace=None)

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

The only difference with the socketio.Server.session() method is that when the namespace argument is not given the namespace associated with the class is used.

trigger_event(event, *args)

Dispatch an event to the proper handler method.

In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed, or if having a single method that catches all events is desired.

AsyncClientNamespace class

class socketio.AsyncClientNamespace(namespace=None)

Base class for asyncio client-side class-based namespaces.

A class-based namespace is a class that contains all the event handlers for a Socket.IO namespace. The event handlers are methods of the class with the prefix on_, such as on_connect, on_disconnect, on_message, on_json, and so on. These can be regular functions or coroutines.

Parameters:

namespace – The Socket.IO namespace to be used with all the event handlers defined in this class. If this argument is omitted, the default namespace is used.

async disconnect()

Disconnect a client.

The only difference with the socketio.Client.disconnect() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

async emit(event, data=None, namespace=None, callback=None)

Emit a custom event to the server.

The only difference with the socketio.Client.emit() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

async send(data, namespace=None, callback=None)

Send a message to the server.

The only difference with the socketio.Client.send() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

async trigger_event(event, *args)

Dispatch an event to the proper handler method.

In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed, or if having a single method that catches all events is desired.

Note: this method is a coroutine.

AsyncNamespace class

class socketio.AsyncNamespace(namespace=None)

Base class for asyncio server-side class-based namespaces.

A class-based namespace is a class that contains all the event handlers for a Socket.IO namespace. The event handlers are methods of the class with the prefix on_, such as on_connect, on_disconnect, on_message, on_json, and so on. These can be regular functions or coroutines.

Parameters:

namespace – The Socket.IO namespace to be used with all the event handlers defined in this class. If this argument is omitted, the default namespace is used.

async close_room(room, namespace=None)

Close a room.

The only difference with the socketio.Server.close_room() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

async disconnect(sid, namespace=None)

Disconnect a client.

The only difference with the socketio.Server.disconnect() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

async emit(event, data=None, room=None, skip_sid=None, namespace=None, callback=None)

Emit a custom event to one or more connected clients.

The only difference with the socketio.Server.emit() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

enter_room(sid, room, namespace=None)

Enter a room.

The only difference with the socketio.Server.enter_room() method is that when the namespace argument is not given the namespace associated with the class is used.

async get_session(sid, namespace=None)

Return the user session for a client.

The only difference with the socketio.Server.get_session() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

leave_room(sid, room, namespace=None)

Leave a room.

The only difference with the socketio.Server.leave_room() method is that when the namespace argument is not given the namespace associated with the class is used.

rooms(sid, namespace=None)

Return the rooms a client is in.

The only difference with the socketio.Server.rooms() method is that when the namespace argument is not given the namespace associated with the class is used.

async save_session(sid, session, namespace=None)

Store the user session for a client.

The only difference with the socketio.Server.save_session() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

async send(data, room=None, skip_sid=None, namespace=None, callback=None)

Send a message to one or more connected clients.

The only difference with the socketio.Server.send() method is that when the namespace argument is not given the namespace associated with the class is used.

Note: this method is a coroutine.

session(sid, namespace=None)

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

The only difference with the socketio.Server.session() method is that when the namespace argument is not given the namespace associated with the class is used.

async trigger_event(event, *args)

Dispatch an event to the proper handler method.

In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed, or if having a single method that catches all events is desired.

Note: this method is a coroutine.

BaseManager class

class socketio.BaseManager

Manage client connections.

This class keeps track of all the clients and the rooms they are in, to support the broadcasting of messages. The data used by this class is stored in a memory structure, making it appropriate only for single process services. More sophisticated storage backends can be implemented by subclasses.

close_room(room, namespace)

Remove all participants from a room.

connect(sid, namespace)

Register a client connection to a namespace.

disconnect(sid, namespace)

Register a client disconnect from a namespace.

emit(event, data, namespace, room=None, skip_sid=None, callback=None, **kwargs)

Emit a message to a single client, a room, or all the clients connected to the namespace.

enter_room(sid, namespace, room)

Add a client to a room.

get_namespaces()

Return an iterable with the active namespace names.

get_participants(namespace, room)

Return an iterable with the active participants in a room.

get_rooms(sid, namespace)

Return the rooms a client is in.

initialize()

Invoked before the first request is received. Subclasses can add their initialization code here.

leave_room(sid, namespace, room)

Remove a client from a room.

pre_disconnect(sid, namespace)

Put the client in the to-be-disconnected list.

This allows the client data structures to be present while the disconnect handler is invoked, but still recognize the fact that the client is soon going away.

trigger_callback(sid, namespace, id, data)

Invoke an application callback.

PubSubManager class

class socketio.PubSubManager(channel='socketio', write_only=False, logger=None)

Manage a client list attached to a pub/sub backend.

This is a base class that enables multiple servers to share the list of clients, with the servers communicating events through a pub/sub backend. The use of a pub/sub backend also allows any client connected to the backend to emit events addressed to Socket.IO clients.

The actual backends must be implemented by subclasses, this class only provides a pub/sub generic framework.

Parameters:

channel – The channel name on which the server sends and receives notifications.

close_room(room, namespace=None)

Remove all participants from a room.

emit(event, data, namespace=None, room=None, skip_sid=None, callback=None, **kwargs)

Emit a message to a single client, a room, or all the clients connected to the namespace.

This method takes care or propagating the message to all the servers that are connected through the message queue.

The parameters are the same as in Server.emit().

initialize()

Invoked before the first request is received. Subclasses can add their initialization code here.

KombuManager class

class socketio.KombuManager(url='amqp://guest:guest@localhost:5672//', channel='socketio', write_only=False, logger=None, connection_options=None, exchange_options=None, queue_options=None, producer_options=None)

Client manager that uses kombu for inter-process messaging.

This class implements a client manager backend for event sharing across multiple processes, using RabbitMQ, Redis or any other messaging mechanism supported by kombu.

To use a kombu backend, initialize the Server instance as follows:

url = 'amqp://user:password@hostname:port//'
server = socketio.Server(client_manager=socketio.KombuManager(url))
Parameters:
  • url – The connection URL for the backend messaging queue. Example connection URLs are 'amqp://guest:guest@localhost:5672//' and 'redis://localhost:6379/' for RabbitMQ and Redis respectively. Consult the kombu documentation for more on how to construct connection URLs.

  • channel – The channel name on which the server sends and receives notifications. Must be the same in all the servers.

  • write_only – If set ot True, only initialize to emit events. The default of False initializes the class for emitting and receiving.

  • connection_options – additional keyword arguments to be passed to kombu.Connection().

  • exchange_options – additional keyword arguments to be passed to kombu.Exchange().

  • queue_options – additional keyword arguments to be passed to kombu.Queue().

  • producer_options – additional keyword arguments to be passed to kombu.Producer().

initialize()

Invoked before the first request is received. Subclasses can add their initialization code here.

RedisManager class

class socketio.RedisManager(url='redis://localhost:6379/0', channel='socketio', write_only=False, logger=None, redis_options=None)

Redis based client manager.

This class implements a Redis backend for event sharing across multiple processes. Only kept here as one more example of how to build a custom backend, since the kombu backend is perfectly adequate to support a Redis message queue.

To use a Redis backend, initialize the Server instance as follows:

url = 'redis://hostname:port/0'
server = socketio.Server(client_manager=socketio.RedisManager(url))
Parameters:
  • url – The connection URL for the Redis server. For a default Redis store running on the same host, use redis://.

  • channel – The channel name on which the server sends and receives notifications. Must be the same in all the servers.

  • write_only – If set ot True, only initialize to emit events. The default of False initializes the class for emitting and receiving.

  • redis_options – additional keyword arguments to be passed to Redis.from_url().

initialize()

Invoked before the first request is received. Subclasses can add their initialization code here.

KafkaManager class

class socketio.KafkaManager(url='kafka://localhost:9092', channel='socketio', write_only=False)

Kafka based client manager.

This class implements a Kafka backend for event sharing across multiple processes.

To use a Kafka backend, initialize the Server instance as follows:

url = 'kafka://hostname:port'
server = socketio.Server(client_manager=socketio.KafkaManager(url))
Parameters:
  • url – The connection URL for the Kafka server. For a default Kafka store running on the same host, use kafka://.

  • channel – The channel name (topic) on which the server sends and receives notifications. Must be the same in all the servers.

  • write_only – If set ot True, only initialize to emit events. The default of False initializes the class for emitting and receiving.

AsyncManager class

class socketio.AsyncManager

Manage a client list for an asyncio server.

async close_room(room, namespace)

Remove all participants from a room.

Note: this method is a coroutine.

connect(sid, namespace)

Register a client connection to a namespace.

disconnect(sid, namespace)

Register a client disconnect from a namespace.

async emit(event, data, namespace, room=None, skip_sid=None, callback=None, **kwargs)

Emit a message to a single client, a room, or all the clients connected to the namespace.

Note: this method is a coroutine.

enter_room(sid, namespace, room)

Add a client to a room.

get_namespaces()

Return an iterable with the active namespace names.

get_participants(namespace, room)

Return an iterable with the active participants in a room.

get_rooms(sid, namespace)

Return the rooms a client is in.

initialize()

Invoked before the first request is received. Subclasses can add their initialization code here.

leave_room(sid, namespace, room)

Remove a client from a room.

pre_disconnect(sid, namespace)

Put the client in the to-be-disconnected list.

This allows the client data structures to be present while the disconnect handler is invoked, but still recognize the fact that the client is soon going away.

async trigger_callback(sid, namespace, id, data)

Invoke an application callback.

Note: this method is a coroutine.

AsyncRedisManager class

class socketio.AsyncRedisManager(url='redis://localhost:6379/0', channel='socketio', write_only=False, logger=None)

Redis based client manager for asyncio servers.

This class implements a Redis backend for event sharing across multiple processes. Only kept here as one more example of how to build a custom backend, since the kombu backend is perfectly adequate to support a Redis message queue.

To use a Redis backend, initialize the Server instance as follows:

server = socketio.Server(client_manager=socketio.AsyncRedisManager(
    'redis://hostname:port/0'))
Parameters:
  • url – The connection URL for the Redis server. For a default Redis store running on the same host, use redis://. To use an SSL connection, use rediss://.

  • channel – The channel name on which the server sends and receives notifications. Must be the same in all the servers.

  • write_only – If set ot True, only initialize to emit events. The default of False initializes the class for emitting and receiving.

AsyncAioPikaManager class

class socketio.AsyncAioPikaManager(url='amqp://guest:guest@localhost:5672//', channel='socketio', write_only=False, logger=None)

Client manager that uses aio_pika for inter-process messaging under asyncio.

This class implements a client manager backend for event sharing across multiple processes, using RabbitMQ

To use a aio_pika backend, initialize the Server instance as follows:

url = 'amqp://user:password@hostname:port//'
server = socketio.Server(client_manager=socketio.AsyncAioPikaManager(
    url))
Parameters:
  • url – The connection URL for the backend messaging queue. Example connection URLs are 'amqp://guest:guest@localhost:5672//' for RabbitMQ.

  • channel – The channel name on which the server sends and receives notifications. Must be the same in all the servers. With this manager, the channel name is the exchange name in rabbitmq

  • write_only – If set ot True, only initialize to emit events. The default of False initializes the class for emitting and receiving.