Clients¶
- 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:
reconnection –
Trueif the client should automatically attempt to reconnect to the server after an interruption, orFalseto not reconnect. The default isTrue.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
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.handle_sigint – Set to
Trueto automatically handle disconnection when the process is interrupted, or toFalseto 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.Sessionobject to be used when sending requests to the server. Use it if you need to add special client options such as proxy servers, SSL certificates, custom CA bundle, etc.ssl_verify –
Trueto verify SSL certificates, orFalseto skip SSL certificate verification, allowing connections to servers with self signed certificates. The default isTrue.websocket_extra_options – Dictionary containing additional keyword arguments passed to
websocket.create_connection().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, 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
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 server. 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.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
TimeoutErrorexception 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 toFalse, 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
waitis set toTrue.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,listordict. 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
sidassociated 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
sidvalues per namespace.
This method returns the
sidfor 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.
- class reason¶
Disconnection reasons.
- CLIENT_DISCONNECT = 'client disconnect'¶
Client-initiated disconnection.
- SERVER_DISCONNECT = 'server disconnect'¶
Server-initiated disconnection.
- 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.
- send(data, namespace=None, callback=None)¶
Send a message to the server.
This function emits an event with the name
'message'. Useemit()to issue custom event names.- Parameters:
data – The data to send to the server. 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.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.
- shutdown()¶
Stop the client.
If the client is connected to a server, it is disconnected. If the client is attempting to reconnect to server, the reconnection attempts are stopped. If the client is not connected to a server and is not attempting to reconnect, then this function does nothing.
- 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:
reconnection –
Trueif the client should automatically attempt to reconnect to the server after an interruption, orFalseto not reconnect. The default isTrue.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
Trueor pass a logger object to use. To disable logging set toFalse. The default isFalse. 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.handle_sigint – Set to
Trueto automatically handle disconnection when the process is interrupted, or toFalseto 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.ClientSessionobject to be used when sending requests to the server. Use it if you need to add special client options such as proxy servers, SSL certificates, custom CA bundle, etc.ssl_verify –
Trueto verify SSL certificates, orFalseto skip SSL certificate verification, allowing connections to servers with self signed certificates. The default isTrue.websocket_extra_options – Dictionary containing additional keyword arguments passed to
websocket.create_connection().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.
- 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
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 server. 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.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
TimeoutErrorexception 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 toFalse, 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
waitis set toTrue.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() await 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,listordict. 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
sidassociated 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
sidvalues per namespace.
This method returns the
sidfor 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.
- class reason¶
Disconnection reasons.
- CLIENT_DISCONNECT = 'client disconnect'¶
Client-initiated disconnection.
- SERVER_DISCONNECT = 'server disconnect'¶
Server-initiated disconnection.
- 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.
- async send(data, namespace=None, callback=None)¶
Send a message to the server.
This function emits an event with the name
'message'. Useemit()to issue custom event names.- Parameters:
data – The data to send to the server. 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.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 shutdown()¶
Stop the client.
If the client is connected to a server, it is disconnected. If the client is attempting to reconnect to server, the reconnection attempts are stopped. If the client is not connected to a server and is not attempting to reconnect, then this function does nothing.
- 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.Taskobject.
- 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.