Servers¶
- 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
Trueor pass a logger object to use. To disable logging set toFalse. The default isFalse. Note that fatal errors are logged even whenloggerisFalse.serializer – The serialization method to use when transmitting packets. Valid values are
'default','pickle','msgpack'and'cbor'. Alternatively, a subclass of thePacketclass with custom implementations of theencode()anddecode()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
dumpsandloadsfunctions that are compatible with the standard library versions. This is a process-wide setting, all instantiated servers and clients must use the same JSON module.async_handlers – If set to
True, event handlers for a client are executed in separate threads. To run handlers for a client synchronously, set toFalse. The default isTrue.always_connect – When set to
False, new connections are provisory until the connect handler returns something other thanFalse, at which point they are accepted. When set toTrue, connections are immediately accepted, and then if the connect handler returnsFalsea disconnect is issued. Set toTrueif 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 ofFalse.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 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 toNone(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 toFalseto disable the monitoring task (not recommended). The default isTrue.transports – The list of allowed transports. Valid transports are
'polling'and'websocket'. Defaults to['polling', 'websocket'].engineio_logger – To enable Engine.IO logging set to
Trueor pass a logger object to use. To disable logging set toFalse. The default isFalse. Note that fatal errors are logged even whenengineio_loggerisFalse.
- 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
TimeoutErrorexception 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,listordict. 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
toparameter.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
TimeoutErrorexception 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 ofFalse.
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 ofFalse.
- 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,listordict. 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
toparameter.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 ofFalse.
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()andsend()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 thesessioncontext 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
Middlewareinstance, but it can be invoked directly when the middleware is not used.- Parameters:
environ – The WSGI environment.
start_response – The WSGI
start_responsefunction.
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
usernameandpassword) 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 returnsTrueif the user is allowed orFalseotherwise. To disable authentication, set this argument toFalse(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 isFalse.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 thesid(session ID) for the client and the WSGI environment dictionary as arguments.The
'disconnect'handler receives thesidfor the client as only argument.The
'message'handler and handlers for custom event names receive thesidfor 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.
- class reason¶
Disconnection reasons.
- CLIENT_DISCONNECT = 'client disconnect'¶
Client-initiated disconnection.
- PING_TIMEOUT = 'ping timeout'¶
Ping timeout.
- SERVER_DISCONNECT = 'server disconnect'¶
Server-initiated disconnection.
- TRANSPORT_CLOSE = 'transport close'¶
Transport close.
- TRANSPORT_ERROR = 'transport error'¶
Transport error.
- register_namespace(namespace_handler)¶
Register a namespace handler object.
- Parameters:
namespace_handler – An instance of a
Namespacesubclass 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'. Useemit()to issue custom event names.- Parameters:
data – The data to send to the client or clients. Data can be of type
str,bytes,listordict. 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
toparameter.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 ofFalse.
- 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
Trueor pass a logger object to use. To disable logging set toFalse. Note that fatal errors are logged even whenloggerisFalse.json – An alternative JSON module to use for encoding and decoding packets. Custom json modules must have
dumpsandloadsfunctions that are compatible with the standard library versions. This is a process-wide setting, all instantiated servers and clients must use the same JSON module.async_handlers – If set to
True, event handlers for a client are executed in separate threads. To run handlers for a client synchronously, set toFalse. The default isTrue.always_connect – When set to
False, new connections are provisory until the connect handler returns something other thanFalse, at which point they are accepted. When set toTrue, connections are immediately accepted, and then if the connect handler returnsFalsea disconnect is issued. Set toTrueif 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 ofFalse.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 toNone(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 toFalseto disable the monitoring task (not recommended). The default isTrue.transports – The list of allowed transports. Valid transports are
'polling'and'websocket'. Defaults to['polling', 'websocket'].engineio_logger – To enable Engine.IO logging set to
Trueor pass a logger object to use. To disable logging set toFalse. The default isFalse. Note that fatal errors are logged even whenengineio_loggerisFalse.
- 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
TimeoutErrorexception 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,listordict. 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
toparameter.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
TimeoutErrorexception 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 ofFalse.
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 ofFalse.
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,listordict. 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
toparameter.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 ofFalse.
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()andsend()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
sessioncontext 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
usernameandpassword) 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 returnsTrueif the user is allowed orFalseotherwise. To disable authentication, set this argument toFalse(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 isFalse.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 thesid(session ID) for the client and the WSGI environment dictionary as arguments.The
'disconnect'handler receives thesidfor the client as only argument.The
'message'handler and handlers for custom event names receive thesidfor 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.
- class reason¶
Disconnection reasons.
- CLIENT_DISCONNECT = 'client disconnect'¶
Client-initiated disconnection.
- PING_TIMEOUT = 'ping timeout'¶
Ping timeout.
- SERVER_DISCONNECT = 'server disconnect'¶
Server-initiated disconnection.
- TRANSPORT_CLOSE = 'transport close'¶
Transport close.
- TRANSPORT_ERROR = 'transport error'¶
Transport error.
- register_namespace(namespace_handler)¶
Register a namespace handler object.
- Parameters:
namespace_handler – An instance of a
Namespacesubclass 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'. Useemit()to issue custom event names.- Parameters:
data – The data to send to the client or clients. Data can be of type
str,bytes,listordict. 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
toparameter.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 ofFalse.
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') async def on_connect(sid, environ): username = authenticate_user(environ) if not username: return False async with eio.session(sid) as session: session['username'] = username @eio.on('message') async 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.Taskobject.
- 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.