API Reference

class socketio.SimpleClient(*args, **kwargs)

A Socket.IO client.

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

The positional and keyword arguments given in the constructor are passed to the underlying socketio.Client() object.

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

Emit an event to the server and wait for a response.

This method issues an emit and waits for the server to provide a response or acknowledgement. If the response does not arrive before the timeout, then a TimeoutError exception is raised.

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.

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

connect(url, headers={}, auth=None, transports=None, namespace='/', socketio_path='socket.io', wait_timeout=5)

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. If a function is provided, the client will invoke it to obtain the URL each time a connection or reconnection is attempted.

  • headers – A dictionary with custom headers to send with the connection request. If a function is provided, the client will invoke it to obtain the headers dictionary each time a connection or reconnection is attempted.

  • auth – Authentication data passed to the server with the connection request, normally a dictionary with one or more string key/value pairs. If a function is provided, the client will invoke it to obtain the authentication data each time a connection or reconnection is attempted.

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

  • namespace – The namespace to connect to as a string. If not given, the default namespace / is used.

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

  • wait_timeout – How long the client should wait for the connection to be established. The default is 5 seconds.

disconnect()

Disconnect from the server.

emit(event, data=None)

Emit an event to the server.

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.

This method schedules the event to be sent out and returns, without actually waiting for its delivery. In cases where the client needs to ensure that the event was received, socketio.SimpleClient.call() should be used instead.

receive(timeout=None)

Wait for an event from the server.

Parameters:

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

The return value is a list with the event name as the first element. If the server included arguments with the event, they are returned as additional list elements.

property sid

The session ID received from the server.

The session ID is not guaranteed to remain constant throughout the life of the connection, as reconnections can cause it to change.

property transport

The name of the transport currently in use.

The transport is returned as a string and can be one of polling and websocket.

class socketio.AsyncSimpleClient(*args, **kwargs)

A Socket.IO client.

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

The positional and keyword arguments given in the constructor are passed to the underlying socketio.AsyncClient() object.

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

Emit an event to the server and wait for a response.

This method issues an emit and waits for the server to provide a response or acknowledgement. If the response does not arrive before the timeout, then a TimeoutError exception is raised.

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.

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

Note: this method is a coroutine.

async connect(url, headers={}, auth=None, transports=None, namespace='/', socketio_path='socket.io', wait_timeout=5)

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. If a function is provided, the client will invoke it to obtain the URL each time a connection or reconnection is attempted.

  • headers – A dictionary with custom headers to send with the connection request. If a function is provided, the client will invoke it to obtain the headers dictionary each time a connection or reconnection is attempted.

  • auth – Authentication data passed to the server with the connection request, normally a dictionary with one or more string key/value pairs. If a function is provided, the client will invoke it to obtain the authentication data each time a connection or reconnection is attempted.

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

  • namespace – The namespace to connect to as a string. If not given, the default namespace / is used.

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

  • wait_timeout – How long the client should wait for the connection. The default is 5 seconds.

Note: this method is a coroutine.

async disconnect()

Disconnect from the server.

Note: this method is a coroutine.

async emit(event, data=None)

Emit an event to the server.

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.

Note: this method is a coroutine.

This method schedules the event to be sent out and returns, without actually waiting for its delivery. In cases where the client needs to ensure that the event was received, socketio.SimpleClient.call() should be used instead.

async receive(timeout=None)

Wait for an event from the server.

Parameters:

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

Note: this method is a coroutine.

The return value is a list with the event name as the first element. If the server included arguments with the event, they are returned as additional list elements.

property sid

The session ID received from the server.

The session ID is not guaranteed to remain constant throughout the life of the connection, as reconnections can cause it to change.

property transport

The name of the transport currently in use.

The transport is returned as a string and can be one of polling and websocket.

class socketio.Client(reconnection=True, reconnection_attempts=0, reconnection_delay=1, reconnection_delay_max=5, randomization_factor=0.5, logger=False, serializer='default', json=None, handle_sigint=True, **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 infinite 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.

  • serializer – The serialization method to use when transmitting packets. Valid values are 'default', 'pickle', 'msgpack' and 'cbor'. Alternatively, a subclass of the Packet class with custom implementations of the encode() and decode() methods can be provided. Client and server must use compatible serializers.

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

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

The Engine.IO configuration supports the following settings:

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

  • 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 the server and wait for the response.

This method issues an emit with a callback and waits for the callback to be invoked before returning. If the callback isn’t invoked before the timeout, then a TimeoutError exception is raised. If the Socket.IO connection drops during the wait, this method still waits until the specified timeout.

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 server 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={}, auth=None, transports=None, namespaces=None, socketio_path='socket.io', wait=True, wait_timeout=1, retry=False)

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. If a function is provided, the client will invoke it to obtain the URL each time a connection or reconnection is attempted.

  • headers – A dictionary with custom headers to send with the connection request. If a function is provided, the client will invoke it to obtain the headers dictionary each time a connection or reconnection is attempted.

  • auth – Authentication data passed to the server with the connection request, normally a dictionary with one or more string key/value pairs. If a function is provided, the client will invoke it to obtain the authentication data each time a connection or reconnection is attempted.

  • 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 namespaces to connect as a string or list of strings. If not given, the namespaces that have registered event handlers are connected.

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

  • wait – if set to True (the default) the call only returns when all the namespaces are connected. If set to False, the call returns as soon as the Engine.IO transport is connected, and the namespaces will connect in the background.

  • wait_timeout – How long the client should wait for the connection. The default is 1 second. This argument is only considered when wait is set to True.

  • retry – Apply the reconnection logic if the initial connection attempt fails. The default is False.

Example usage:

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

Indicates if the client is connected or not.

disconnect()

Disconnect from the server.

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

Emit a custom event to the server.

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 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)
get_sid(namespace=None)

Return the sid associated with a connection.

Parameters:

namespace – The Socket.IO namespace. If this argument is omitted the handler is associated with the default namespace. Note that unlike previous versions, the current version of the Socket.IO protocol uses different sid values per namespace.

This method returns the sid for the requested namespace as a string.

namespaces

set of connected namespaces.

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. The '*' event name can be used to define a catch-all event handler.

  • 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. A catch-all namespace can be defined by passing '*' as the 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 arguments passed to the handler function depend on the event type:

  • The 'connect' event handler does not take arguments.

  • The 'disconnect' event handler does not take 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.

  • A catch-all event handler receives the event name as first argument, followed by any arguments specific to the event.

  • A catch-all namespace event handler receives the namespace as first argument, followed by any arguments specific to the event.

  • A combined catch-all namespace and catch-all event handler receives the event name as first argument and the namespace as second argument, followed by any arguments specific to the event.

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

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 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 that represents the background task, on which the join() methond can be invoked to wait for the task to complete.

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.

class socketio.AsyncClient(reconnection=True, reconnection_attempts=0, reconnection_delay=1, reconnection_delay_max=5, randomization_factor=0.5, logger=False, serializer='default', json=None, handle_sigint=True, **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 infinite 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.

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

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

The Engine.IO configuration supports the following settings:

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

  • 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 the server and wait for the response.

This method issues an emit with a callback and waits for the callback to be invoked before returning. If the callback isn’t invoked before the timeout, then a TimeoutError exception is raised. If the Socket.IO connection drops during the wait, this method still waits until the specified timeout.

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 server 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={}, auth=None, transports=None, namespaces=None, socketio_path='socket.io', wait=True, wait_timeout=1, retry=False)

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. If a function is provided, the client will invoke it to obtain the URL each time a connection or reconnection is attempted.

  • headers – A dictionary with custom headers to send with the connection request. If a function is provided, the client will invoke it to obtain the headers dictionary each time a connection or reconnection is attempted.

  • auth – Authentication data passed to the server with the connection request, normally a dictionary with one or more string key/value pairs. If a function is provided, the client will invoke it to obtain the authentication data each time a connection or reconnection is attempted.

  • 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 namespaces to connect as a string or list of strings. If not given, the namespaces that have registered event handlers are connected.

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

  • wait – if set to True (the default) the call only returns when all the namespaces are connected. If set to False, the call returns as soon as the Engine.IO transport is connected, and the namespaces will connect in the background.

  • wait_timeout – How long the client should wait for the connection. The default is 1 second. This argument is only considered when wait is set to True.

  • retry – Apply the reconnection logic if the initial connection attempt fails. The default is False.

Note: this method is a coroutine.

Example usage:

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

Indicates if the client is connected or not.

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

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 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)
get_sid(namespace=None)

Return the sid associated with a connection.

Parameters:

namespace – The Socket.IO namespace. If this argument is omitted the handler is associated with the default namespace. Note that unlike previous versions, the current version of the Socket.IO protocol uses different sid values per namespace.

This method returns the sid for the requested namespace as a string.

namespaces

set of connected namespaces.

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. The '*' event name can be used to define a catch-all event handler.

  • 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. A catch-all namespace can be defined by passing '*' as the 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 arguments passed to the handler function depend on the event type:

  • The 'connect' event handler does not take arguments.

  • The 'disconnect' event handler does not take 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.

  • A catch-all event handler receives the event name as first argument, followed by any arguments specific to the event.

  • A catch-all namespace event handler receives the namespace as first argument, followed by any arguments specific to the event.

  • A combined catch-all namespace and catch-all event handler receives the event name as first argument and the namespace as second argument, followed by any arguments specific to the event.

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

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

The return value is a asyncio.Task object.

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.

class socketio.Server(client_manager=None, logger=False, serializer='default', json=None, async_handlers=True, always_connect=False, namespaces=None, **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.

  • serializer – The serialization method to use when transmitting packets. Valid values are 'default', 'pickle', 'msgpack' and 'cbor'. Alternatively, a subclass of the Packet class with custom implementations of the encode() and decode() methods can be provided. Client and server must use compatible serializers.

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

  • namespaces – a list of namespaces that are accepted, in addition to any namespaces for which handlers have been defined. The default is [‘/’], which always accepts connections to the default namespace. Set to ‘*’ to accept all namespaces.

  • 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_interval – The interval in seconds at which the server pings the client. The default is 25 seconds. For advanced control, a two element tuple can be given, where the first number is the ping interval and the second is a grace period added by the server.

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

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

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

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

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

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

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

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

  • 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, ignore_queue=False)

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

This method issues an emit with a callback and waits for the callback to be invoked before returning. If the callback isn’t invoked before the timeout, then a TimeoutError exception is raised. If the Socket.IO connection drops during the wait, this method still waits until the specified timeout.

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, ignore_queue=False)

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, to any custom room created by the application to address all the clients in that room, or to a list of custom room names. 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 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_environ(sid, namespace=None)

Return the WSGI environ dictionary for a client.

Parameters:
  • sid – The session of the client.

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

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.

instrument(auth=None, mode='development', read_only=False, server_id=None, namespace='/admin', server_stats_interval=2)

Instrument the Socket.IO server for monitoring with the Socket.IO Admin UI.

Parameters:
  • auth – Authentication credentials for Admin UI access. Set to a dictionary with the expected login (usually username and password) or a list of dictionaries if more than one set of credentials need to be available. For more complex authentication methods, set to a callable that receives the authentication dictionary as an argument and returns True if the user is allowed or False otherwise. To disable authentication, set this argument to False (not recommended, never do this on a production server).

  • mode – The reporting mode. The default is 'development', which is best used while debugging, as it may have a significant performance effect. Set to 'production' to reduce the amount of information that is reported to the admin UI.

  • read_only – If set to True, the admin interface will be read-only, with no option to modify room assignments or disconnect clients. The default is False.

  • server_id – The server name to use for this server. If this argument is omitted, the server generates its own name.

  • namespace – The Socket.IO namespace to use for the admin interface. The default is /admin.

  • server_stats_interval – The interval in seconds at which the server emits a summary of it stats to all connected admins.

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. The '*' event name can be used to define a catch-all event handler.

  • 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. A catch-all namespace can be defined by passing '*' as the namespace.

Example usage:

# as a decorator:
@sio.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)
    sio.send(sid, 'response')
socket_io.on('message', namespace='/chat', handler=message_handler)

The arguments passed to the handler function depend on the event type:

  • The 'connect' event handler receives the sid (session ID) for the client and the WSGI environment dictionary as arguments.

  • The 'disconnect' handler receives the sid for the client as only argument.

  • The 'message' handler and handlers for custom event names receive the sid for the client and the message payload as arguments. Any values returned from a message handler will be passed to the client’s acknowledgement callback function if it exists.

  • A catch-all event handler receives the event name as first argument, followed by any arguments specific to the event.

  • A catch-all namespace event handler receives the namespace as first argument, followed by any arguments specific to the event.

  • A combined catch-all namespace and catch-all event handler receives the event name as first argument and the namespace as second argument, followed by any arguments specific to the event.

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, ignore_queue=False)

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, to any any custom room created by the application to address all the clients in that room, or to a list of custom room names. 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 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'])
shutdown()

Stop Socket.IO background tasks.

This method stops all background activity initiated by the Socket.IO server. It must be called before shutting down the web 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 that represents the background task, on which the join() methond can be invoked to wait for the task to complete.

transport(sid, namespace=None)

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.

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

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

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

  • namespaces – a list of namespaces that are accepted, in addition to any namespaces for which handlers have been defined. The default is [‘/’], which always accepts connections to the default namespace. Set to ‘*’ to accept all namespaces.

  • 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”, “sanic”, “tornado” and “asgi”. If this argument is not given, “aiohttp” is tried first, followed by “sanic”, “tornado”, and finally “asgi”. The first async mode that has all its dependencies installed is the one that is chosen.

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

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

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

  • allow_upgrades – Whether to allow transport upgrades or not. 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 to the 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.

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

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, ignore_queue=False)

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

This method issues an emit with a callback and waits for the callback to be invoked before returning. If the callback isn’t invoked before the timeout, then a TimeoutError exception is raised. If the Socket.IO connection drops during the wait, this method still waits until the specified timeout.

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, ignore_queue=False)

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, to any any custom room created by the application to address all the clients in that room, or to a list of custom room names. 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 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.

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

Note: 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)
get_environ(sid, namespace=None)

Return the WSGI environ dictionary for a client.

Parameters:
  • sid – The session of the client.

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

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.

instrument(auth=None, mode='development', read_only=False, server_id=None, namespace='/admin', server_stats_interval=2)

Instrument the Socket.IO server for monitoring with the Socket.IO Admin UI.

Parameters:
  • auth – Authentication credentials for Admin UI access. Set to a dictionary with the expected login (usually username and password) or a list of dictionaries if more than one set of credentials need to be available. For more complex authentication methods, set to a callable that receives the authentication dictionary as an argument and returns True if the user is allowed or False otherwise. To disable authentication, set this argument to False (not recommended, never do this on a production server).

  • mode – The reporting mode. The default is 'development', which is best used while debugging, as it may have a significant performance effect. Set to 'production' to reduce the amount of information that is reported to the admin UI.

  • read_only – If set to True, the admin interface will be read-only, with no option to modify room assignments or disconnect clients. The default is False.

  • server_id – The server name to use for this server. If this argument is omitted, the server generates its own name.

  • namespace – The Socket.IO namespace to use for the admin interface. The default is /admin.

  • server_stats_interval – The interval in seconds at which the server emits a summary of it stats to all connected admins.

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

Note: this method is a coroutine.

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. The '*' event name can be used to define a catch-all event handler.

  • 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. A catch-all namespace can be defined by passing '*' as the namespace.

Example usage:

# as a decorator:
@sio.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)
    sio.send(sid, 'response')
socket_io.on('message', namespace='/chat', handler=message_handler)

The arguments passed to the handler function depend on the event type:

  • The 'connect' event handler receives the sid (session ID) for the client and the WSGI environment dictionary as arguments.

  • The 'disconnect' handler receives the sid for the client as only argument.

  • The 'message' handler and handlers for custom event names receive the sid for the client and the message payload as arguments. Any values returned from a message handler will be passed to the client’s acknowledgement callback function if it exists.

  • A catch-all event handler receives the event name as first argument, followed by any arguments specific to the event.

  • A catch-all namespace event handler receives the namespace as first argument, followed by any arguments specific to the event.

  • A combined catch-all namespace and catch-all event handler receives the event name as first argument and the namespace as second argument, followed by any arguments specific to the event.

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, ignore_queue=False)

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, to any any custom room created by the application to address all the clients in that room, or to a list of custom room names. 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 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 shutdown()

Stop Socket.IO background tasks.

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

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.

transport(sid, namespace=None)

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.

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

class socketio.exceptions.ConnectionRefusedError(*args)

Connection refused exception.

This exception can be raised from a connect handler when the connection is not accepted. The positional arguments provided with the exception are returned with the error packet to the client.

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)
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. With a value of None, all incoming traffic is directed to the Socket.IO server, with the assumption that routing, if necessary, is handled by a different layer. When this option is set to None, static_files and other_asgi_app are ignored.

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

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

Example usage:

import socketio
import uvicorn

sio = socketio.AsyncServer()
app = socketio.ASGIApp(sio, static_files={
    '/': 'index.html',
    '/static': './public',
})
uvicorn.run(app, host='127.0.0.1', port=5000)
class socketio.Middleware(socketio_app, wsgi_app=None, socketio_path='socket.io')

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

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.

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

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

The only difference with the socketio.Client.call() method is that when the namespace argument is not given the namespace associated with the class 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, 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 overridden if special dispatching rules are needed, or if having a single method that catches all events is desired.

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.

call(event, data=None, to=None, sid=None, namespace=None, timeout=None, ignore_queue=False)

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

The only difference with the socketio.Server.call() method is that when the namespace argument is not given the namespace associated with the class 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, to=None, room=None, skip_sid=None, namespace=None, callback=None, ignore_queue=False)

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, to=None, room=None, skip_sid=None, namespace=None, callback=None, ignore_queue=False)

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 overridden if special dispatching rules are needed, or if having a single method that catches all events is desired.

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 call(event, data=None, namespace=None, timeout=None)

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

The only difference with the socketio.Client.call() method is that when the namespace argument is not given the namespace associated with the class 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 overridden if special dispatching rules are needed, or if having a single method that catches all events is desired.

Note: this method is a coroutine.

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 call(event, data=None, to=None, sid=None, namespace=None, timeout=None, ignore_queue=False)

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

The only difference with the socketio.Server.call() method is that when the namespace argument is not given the namespace associated with the class 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, to=None, room=None, skip_sid=None, namespace=None, callback=None, ignore_queue=False)

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.

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

Note: this method is a coroutine.

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.

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

Note: this method is a coroutine.

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, to=None, room=None, skip_sid=None, namespace=None, callback=None, ignore_queue=False)

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 overridden if special dispatching rules are needed, or if having a single method that catches all events is desired.

Note: this method is a coroutine.

class socketio.Manager

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(eio_sid, namespace)

Register a client connection to a namespace.

disconnect(sid, namespace, **kwargs)

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, eio_sid=None)

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, id, data)

Invoke an application callback.

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.

connect(eio_sid, namespace)

Register a client connection to a namespace.

disconnect(sid, namespace=None, **kwargs)

Register a client disconnect from a namespace.

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

enter_room(sid, namespace, room, eio_sid=None)

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, id, data)

Invoke an application callback.

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 to 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().

close_room(room, namespace=None)

Remove all participants from a room.

connect(eio_sid, namespace)

Register a client connection to a namespace.

disconnect(sid, namespace=None, **kwargs)

Register a client disconnect from a namespace.

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

enter_room(sid, namespace, room, eio_sid=None)

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, id, data)

Invoke an application callback.

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://. 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 to 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().

close_room(room, namespace=None)

Remove all participants from a room.

connect(eio_sid, namespace)

Register a client connection to a namespace.

disconnect(sid, namespace=None, **kwargs)

Register a client disconnect from a namespace.

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

enter_room(sid, namespace, room, eio_sid=None)

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, id, data)

Invoke an application callback.

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://. For a highly available deployment of Kafka, pass a list with all the connection URLs available in your cluster.

  • 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 to True, only initialize to emit events. The default of False initializes the class for emitting and receiving.

close_room(room, namespace=None)

Remove all participants from a room.

connect(eio_sid, namespace)

Register a client connection to a namespace.

disconnect(sid, namespace=None, **kwargs)

Register a client disconnect from a namespace.

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

enter_room(sid, namespace, room, eio_sid=None)

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, id, data)

Invoke an application callback.

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.

async connect(eio_sid, namespace)

Register a client connection to a namespace.

Note: this method is a coroutine.

async disconnect(sid, namespace, **kwargs)

Disconnect a client.

Note: this method is a coroutine.

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.

async enter_room(sid, namespace, room, eio_sid=None)

Add a client to a room.

Note: this method is a coroutine.

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.

async leave_room(sid, namespace, room)

Remove a client from a room.

Note: this method is a coroutine.

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, id, data)

Invoke an application callback.

Note: this method is a coroutine.

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

Redis based client manager for asyncio servers.

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

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

url = 'redis://hostname:port/0'
server = socketio.AsyncServer(
    client_manager=socketio.AsyncRedisManager(url))
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 to 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 aioredis.from_url().

async close_room(room, namespace=None)

Remove all participants from a room.

Note: this method is a coroutine.

async connect(eio_sid, namespace)

Register a client connection to a namespace.

Note: this method is a coroutine.

async disconnect(sid, namespace, **kwargs)

Disconnect a client.

Note: this method is a coroutine.

async 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().

Note: this method is a coroutine.

async enter_room(sid, namespace, room, eio_sid=None)

Add a client to a room.

Note: this method is a coroutine.

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.

async leave_room(sid, namespace, room)

Remove a client from a room.

Note: this method is a coroutine.

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, id, data)

Invoke an application callback.

Note: this method is a coroutine.

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 to True, only initialize to emit events. The default of False initializes the class for emitting and receiving.

async close_room(room, namespace=None)

Remove all participants from a room.

Note: this method is a coroutine.

async connect(eio_sid, namespace)

Register a client connection to a namespace.

Note: this method is a coroutine.

async disconnect(sid, namespace, **kwargs)

Disconnect a client.

Note: this method is a coroutine.

async 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().

Note: this method is a coroutine.

async enter_room(sid, namespace, room, eio_sid=None)

Add a client to a room.

Note: this method is a coroutine.

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.

async leave_room(sid, namespace, room)

Remove a client from a room.

Note: this method is a coroutine.

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, id, data)

Invoke an application callback.

Note: this method is a coroutine.