### Install python-socketio Client Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/client.md Installs the standard Python client for Socket.IO. This command includes the necessary dependencies for basic client functionality. ```bash pip install "python-socketio[client]" ``` -------------------------------- ### Install Redis client for Socket.IO Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md This command installs the necessary Python Redis client library, which is a prerequisite for using Redis as a message queue with the socket.io.Server class. ```bash pip install redis ``` -------------------------------- ### Install python-socketio Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Installs the Socket.IO server package and its dependencies using pip. This is the first step to using the library. ```bash pip install python-socketio ``` -------------------------------- ### Configure gevent with uWSGI for Socket.IO Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md This snippet shows how to initialize a Socket.IO server using the 'gevent_uwsgi' async mode. It also provides a command-line example for starting a uWSGI server with WebSocket support. ```python import socketio sio = socketio.Server(async_mode='gevent_uwsgi') ``` ```bash $ uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file latency.py --callable app ``` -------------------------------- ### Eventlet Python Socket.IO Server Example Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/intro.md A basic Socket.IO server example using the Eventlet asynchronous framework. It sets up a WSGI application, handles client connections, messages, and disconnections. Requires the eventlet library. ```python import eventlet import socketio sio = socketio.Server() app = socketio.WSGIApp(sio, static_files={ '/': {'content_type': 'text/html', 'filename': 'index.html'} }) @sio.event def connect(sid, environ): print('connect ', sid) @sio.event def my_message(sid, data): print('message ', data) @sio.event def disconnect(sid): print('disconnect ', sid) if __name__ == '__main__': eventlet.wsgi.server(eventlet.listen(('', 5000)), app) ``` -------------------------------- ### Install python-socketio Asyncio Client Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/client.md Installs the asyncio-compatible client for Socket.IO. This command includes dependencies specifically for asynchronous applications. ```bash pip install "python-socketio[asyncio_client]" ``` -------------------------------- ### Running Uvicorn Server Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Command-line instructions to start an ASGI application with Uvicorn. Assumes the application is in a file named 'module' and the ASGI app instance is named 'app'. ```bash uvicorn --port 5000 module:app ``` -------------------------------- ### AsyncServer Engine.IO Configuration (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Shows how to configure the underlying Engine.IO server settings when creating an `AsyncServer` instance. This example sets the asynchronous mode to 'asgi', customizes ping intervals and timeouts, and adjusts buffer sizes and compression settings. ```python import socketio sio = socketio.AsyncServer( async_mode='asgi', ping_interval=(10, 5), # Ping every 10s, grace period of 5s ping_timeout=30, max_http_buffer_size=2000000, http_compression=False, compression_threshold=512 ) ``` -------------------------------- ### Install AioPika for Async RabbitMQ Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Installs the aio-pika package, which provides asynchronous support for RabbitMQ in asyncio applications. This is necessary for using RabbitMQ with socketio.AsyncServer. ```bash pip install aio_pika ``` -------------------------------- ### Asyncio Python Socket.IO Client Example Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/intro.md An example of an asynchronous Python Socket.IO client using asyncio. It demonstrates connecting to a server, handling events, and emitting messages asynchronously. Requires Python 3.5+. ```python import asyncio import socketio sio = socketio.AsyncClient() @sio.event async def connect(): print('connection established') @sio.event async def my_message(data): print('message received with ', data) await sio.emit('my response', {'response': 'my response'}) @sio.event async def disconnect(): print('disconnected from server') async def main(): await sio.connect('http://localhost:5000') await sio.wait() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Configure Eventlet for Socket.IO Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Shows how to initialize a Socket.IO server with Eventlet and deploy it as a WSGI application using eventlet.wsgi.server. It also includes an example of running with Gunicorn. ```python import eventlet import socketio sio = socketio.Server(async_mode='eventlet') app = socketio.WSGIApp(sio) eventlet.wsgi.server(eventlet.listen(('', 8000)), app) ``` ```bash $ gunicorn -k eventlet -w 1 module:app ``` -------------------------------- ### Initialize SocketIO Server with AsyncAioPikaManager Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_manager.md Demonstrates how to initialize a SocketIO Server instance using the AsyncAioPikaManager for inter-process communication. This setup is crucial for distributing events across multiple server instances. ```python import socketio url = 'amqp://user:password@hostname:port//' server = socketio.Server(client_manager=socketio.AsyncAioPikaManager( url)) ``` -------------------------------- ### Python Socket.IO Client Example Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/intro.md A basic example of a Python Socket.IO client that connects to a server, handles events like 'connect', 'my_message', and 'disconnect', and emits responses. It uses the standard Python socketio client. ```python import socketio sio = socketio.Client() @sio.event def connect(): print('connection established') @sio.event def my_message(data): print('message received with ', data) sio.emit('my response', {'response': 'my response'}) @sio.event def disconnect(): print('disconnected from server') sio.connect('http://localhost:5000') sio.wait() ``` -------------------------------- ### Asyncio Python Socket.IO Server Example with Uvicorn Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/intro.md An asynchronous Socket.IO server example using asyncio and the Uvicorn web server with aiohttp. It defines event handlers for connection, messages, and disconnections, and serves a static index.html file. Requires Python 3.5+ and aiohttp. ```python from aiohttp import web import socketio sio = socketio.AsyncServer() app = web.Application() sio.attach(app) async def index(request): """Serve the client-side application.""" with open('index.html') as f: return web.Response(text=f.read(), content_type='text/html') @sio.event def connect(sid, environ): print("connect ", sid) @sio.event async def chat_message(sid, data): print("message ", data) @sio.event def disconnect(sid): print('disconnect ', sid) app.router.add_static('/static', 'static') app.router.add_get('/', index) if __name__ == '__main__': web.run_app(app) ``` -------------------------------- ### Install Kombu for Message Queues Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Installs the Kombu Python package, which provides access to RabbitMQ and other message queues. Additional packages may be needed for specific queue types, such as 'redis' for Redis queues. ```bash pip install kombu ``` -------------------------------- ### Connect Socket.IO Client to Server (Python and Asyncio) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/client.md Illustrates connecting a Socket.IO client to a server using the `connect()` method. Includes examples for both standard Python and asyncio, and shows how to specify the transport protocol. ```python sio.connect('http://localhost:5000') # asyncio await sio.connect('http://localhost:5000') sio.connect('http://localhost:5000', transports=['websocket']) ``` -------------------------------- ### Initialize AsyncServer with AsyncRedisManager Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_manager.md Demonstrates how to initialize an AsyncServer with a Redis-based client manager for inter-process communication. This setup is crucial for scaling Socket.IO applications across multiple processes. ```python import socketio url = 'redis://hostname:port/0' server = socketio.AsyncServer( client_manager=socketio.AsyncRedisManager(url)) ``` -------------------------------- ### Initialize Socket.IO Server with RedisManager Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_manager.md Demonstrates how to initialize a Socket.IO Server instance using the RedisManager for cross-process communication. This setup is crucial for scaling Socket.IO applications across multiple server instances. ```python import socketio url = 'redis://hostname:port/0' server = socketio.Server(client_manager=socketio.RedisManager(url)) ``` -------------------------------- ### Initialize Socket.IO Server with KombuManager Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_manager.md Demonstrates how to initialize a Socket.IO Server instance using the KombuManager for inter-process communication. This setup is crucial for distributing events across multiple server instances. ```python import socketio url = 'amqp://user:password@hostname:port//' server = socketio.Server(client_manager=socketio.KombuManager(url)) ``` -------------------------------- ### Managing Background Tasks with Python Socket.IO Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_client.md Illustrates how to start and manage background tasks using the `start_background_task` utility. This function abstracts the underlying asynchronous model, allowing tasks to be run without explicit async/await syntax in the main application code. ```python import socketio import time sio = socketio.Client() def my_background_task(arg1, arg2): print(f'Background task started with {arg1} and {arg2}') time.sleep(5) # Simulate work print('Background task finished') # Start a background task task = sio.start_background_task(target=my_background_task, arg1='hello', arg2=123) # Optionally, wait for the task to complete task.join() print('Main thread continuing after task completion.') ``` -------------------------------- ### JavaScript Socket.IO Client Connection and Event Handling Source: https://github.com/miguelgrinberg/python-socketio/blob/main/examples/server/wsgi/templates/index.html Establishes a connection to the Socket.IO server and sets up event listeners for 'connect', 'disconnect', and custom events like 'my_response'. It also includes handlers for form submissions to emit data to the server. ```javascript $(document).ready(function(){ var socket = io.connect(); socket.on('connect', function() { socket.emit('my_event', {data: 'I\'m connected!'}); }); socket.on('disconnect', function(reason) { $('#log').append('
Disconnected: ' + reason); }); socket.on('my_response', function(msg) { $('#log').append('
Received: ' + msg.data); }); // event handler for server sent data // the data is displayed in the "Received" section of the page // handlers for the different forms in the page // these send data to the server in a variety of ways $('form#emit').submit(function(event) { socket.emit('my_event', {data: $('#emit_data').val()}); return false; }); $('form#broadcast').submit(function(event) { socket.emit('my_broadcast_event', {data: $('#broadcast_data').val()}); return false; }); $('form#join').submit(function(event) { socket.emit('join', {room: $('#join_room').val()}); return false; }); $('form#leave').submit(function(event) { socket.emit('leave', {room: $('#leave_room').val()}); return false; }); $('form#send_room').submit(function(event) { socket.emit('my_room_event', {room: $('#room_name').val(), data: $('#room_data').val()}); return false; }); $('form#close').submit(function(event) { socket.emit('close_room', {room: $('#close_room').val()}); return false; }); $('form#disconnect').submit(function(event) { socket.emit('disconnect_request'); return false; }); }); ``` -------------------------------- ### Deploy Socket.IO with Gunicorn (Shell) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Provides a command-line example for deploying a Python Socket.IO application using Gunicorn. This command specifies the number of workers and threads, and the bind address, enabling efficient handling of concurrent clients. ```bash gunicorn --workers 1 --threads 100 --bind 127.0.0.1:5000 module:app ``` -------------------------------- ### Python Socket.IO Class-Based Namespace Example Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Demonstrates a basic class-based namespace implementation for a standard Python Socket.IO server. It shows how to define connect, disconnect, and custom event handlers within a namespace subclass. The namespace is then registered with the Socket.IO server. ```python class MyCustomNamespace(socketio.Namespace): def on_connect(self, sid, environ): pass def on_disconnect(self, sid, reason): pass def on_my_event(self, sid, data): self.emit('my_response', data) sio.register_namespace(MyCustomNamespace('/test')) ``` -------------------------------- ### JavaScript Socket.IO Client for Python Server Source: https://github.com/miguelgrinberg/python-socketio/blob/main/examples/server/aiohttp/app.html This snippet demonstrates how to establish a WebSocket connection using Socket.IO, send events to the server, and receive data. It includes handlers for connection, disconnection, and custom events, as well as form submissions to send data to different event namespaces. ```javascript $(document).ready(function(){ var socket = io.connect(); socket.on('connect', function() { socket.emit('my_event', {data: 'I\'m connected!'}); }); socket.on('disconnect', function(reason) { $('#log').append('
Disconnected: ' + reason); }); socket.on('my_response', function(msg) { $('#log').append('
Received: ' + msg.data); }); // event handler for server sent data // the data is displayed in the "Received" section of the page // handlers for the different forms in the page // these send data to the server in a variety of ways $('form#emit').submit(function(event) { socket.emit('my_event', {data: $('#emit_data').val()}); return false; }); $('form#broadcast').submit(function(event) { socket.emit('my_broadcast_event', {data: $('#broadcast_data').val()}); return false; }); $('form#join').submit(function(event) { socket.emit('join', {room: $('#join_room').val()}); return false; }); $('form#leave').submit(function(event) { socket.emit('leave', {room: $('#leave_room').val()}); return false; }); $('form#send_room').submit(function(event) { socket.emit('my_room_event', {room: $('#room_name').val(), data: $('#room_data').val()}); return false; }); $('form#close').submit(function(event) { socket.emit('close_room', {room: $('#close_room').val()}); return false; }); $('form#disconnect').submit(function(event) { socket.emit('disconnect_request'); return false; }); }); ``` -------------------------------- ### KafkaManager: Get Room Participants Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_manager.md Returns an iterable of active participants within a specified room and namespace. Note: In multi-server setups, this only lists participants connected to the current server. ```python kafka_manager.get_participants(namespace, room) ``` -------------------------------- ### Configure AsyncServer with Custom Parameters (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Demonstrates initializing `AsyncServer` with custom parameters. This includes enabling logging, specifying a custom JSON module, disabling asynchronous handlers, and configuring Engine.IO settings like CORS origins and allowed transports. ```python import socketio import json sio = socketio.AsyncServer( logger=True, json=json, async_handlers=False, cors_allowed_origins='*', transports=['polling', 'websocket'] ) ``` -------------------------------- ### Client Instantiation Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/client.md Demonstrates how to create instances of both standard Python and asyncio Socket.IO clients. ```APIDOC ## Creating a Client Instance To instantiate an Socket.IO client, simply create an instance of the appropriate client class: ```python import socketio # standard Python sio = socketio.Client() # asyncio sio = socketio.AsyncClient() ``` ``` -------------------------------- ### socketio.Server Initialization Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Configuration options for initializing a Socket.IO server instance. ```APIDOC ## socketio.Server Constructor ### Description Initializes a Socket.IO server with various configuration options for transports, serialization, and connection handling. ### Method Constructor ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **client_manager** (object) - Optional - The client manager instance to manage client connections. Defaults to an in-memory structure. * **logger** (bool or object) - Optional - Enable logging by setting to `True` or passing a logger object. Defaults to `False`. * **serializer** (str or object) - Optional - Serialization method for packets. Valid values: `'default'`, `'pickle'`, `'msgpack'`, `'cbor'`, or a custom `Packet` subclass. Defaults to `'default'`. * **json** (module) - Optional - An alternative JSON module with `dumps` and `loads` functions. Must be compatible with the standard library. * **async_handlers** (bool) - Optional - If `True`, event handlers are executed in separate threads. Defaults to `True`. * **always_connect** (bool) - Optional - If `True`, connections are immediately accepted. Defaults to `False`. * **namespaces** (list or str) - Optional - List of accepted namespaces. Defaults to `['/']`. Set to `'*'` to accept all namespaces. * **kwargs** (dict) - Optional - Connection parameters for the underlying Engine.IO server. ### Engine.IO Connection Parameters (within kwargs) * **async_mode** (str) - Optional - Asynchronous model to use (`'threading'`, `'eventlet'`, `'gevent'`, `'gevent_uwsgi'`). Defaults to the first available mode with installed dependencies. * **ping_interval** (int or tuple) - Optional - Interval in seconds for server pings. Can be a single value or a tuple `(interval, grace_period)`. Defaults to 25 seconds. * **ping_timeout** (int) - Optional - Time in seconds for client to respond to ping before disconnecting. Defaults to 20 seconds. * **max_http_buffer_size** (int) - Optional - Maximum size for incoming messages in bytes. Defaults to 1,000,000 bytes. * **allow_upgrades** (bool) - Optional - Whether to allow transport upgrades. Defaults to `True`. * **http_compression** (bool) - Optional - Whether to compress packages for the polling transport. Defaults to `True`. * **compression_threshold** (int) - Optional - Minimum byte size for messages to be compressed. Defaults to 1024 bytes. * **cookie** (str or dict or None) - Optional - Name of the cookie for client session ID, or a dictionary for attributes, or `None` to disable. Defaults to `None`. * **cors_allowed_origins** (str or list) - Optional - Origin(s) allowed to connect. Defaults to the same origin. Set to `'*'` to allow all, or `[]` to disable. * **cors_credentials** (bool) - Optional - Whether credentials (cookies, authentication) are allowed. Defaults to `True`. ### Request Example ```python import socketio sio = socketio.Server( async_handlers=True, cors_allowed_origins='*' ) ``` ### Response N/A (Constructor does not return a value, but initializes the server object.) ``` -------------------------------- ### Install Kafka-Python for Kafka Integration Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Installs the kafka-python package required for integrating Socket.IO with Apache Kafka. This enables Socket.IO to use Kafka as a message broker. ```bash pip install kafka-python ``` -------------------------------- ### Create Socket.IO Server Instances (Python) Source: https://context7.com/miguelgrinberg/python-socketio/llms.txt Demonstrates creating both standard synchronous and asyncio-compatible Socket.IO server instances using `socketio.Server` and `socketio.AsyncServer`. Configuration options for transports, CORS, logging, and buffer sizes are shown. ```python import socketio # Standard synchronous server sio = socketio.Server( async_mode='threading', cors_allowed_origins='*', logger=True, engineio_logger=True, ping_interval=25, ping_timeout=20 ) # Asyncio server sio_async = socketio.AsyncServer( async_mode='asgi', cors_allowed_origins=['http://localhost:3000', 'https://myapp.com'], max_http_buffer_size=1000000 ) ``` -------------------------------- ### Middlewares Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api.md Documentation for WSGIApp, ASGIApp, and Middleware, detailing how to integrate SocketIO with web frameworks. ```APIDOC ## Middlewares ### Description This section describes `WSGIApp`, `ASGIApp`, and `Middleware`, which are used for integrating SocketIO with WSGI and ASGI compatible web frameworks, enabling middleware functionality. ### Endpoints Details the classes and their usage. #### `socketio.WSGIApp` * Used to wrap a SocketIO server to be compatible with WSGI applications. #### `socketio.ASGIApp` * Used to wrap a SocketIO server to be compatible with ASGI applications. #### `socketio.Middleware` * A base class for creating custom middleware for SocketIO servers. ``` -------------------------------- ### Enter Room (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Asynchronously adds a client to a specified room. This allows events to be broadcasted to all clients within that room using emit() or send(). If the room does not exist, it will be created. ```python async def enter_room(self, 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 (str): Session ID of the client. room (str): Room name. If the room does not exist it is created. namespace (str): The Socket.IO namespace. Defaults to the default namespace. """ pass ``` -------------------------------- ### Start Background Task (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Starts a background task using the appropriate asynchronous model. This utility function simplifies the process of running coroutines concurrently without manual management of the event loop. It returns an asyncio.Task object. ```python def 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. """ pass ``` -------------------------------- ### Server Creation Source: https://context7.com/miguelgrinberg/python-socketio/llms.txt Demonstrates how to create both standard synchronous and asyncio-compatible Socket.IO servers with various configuration options. ```APIDOC ## Server Creation ### Description Creates a Socket.IO server instance. Supports both standard synchronous (`socketio.Server`) and asyncio-compatible (`socketio.AsyncServer`) implementations. Configuration options include `async_mode`, CORS origins, logging, ping intervals, timeouts, and buffer sizes. ### Method Instantiate `socketio.Server` or `socketio.AsyncServer` ### Parameters #### Standard Server (`socketio.Server`) - **async_mode** (str) - Optional - 'threading' or 'eventlet' or 'gevent'. Defaults to 'threading'. - **cors_allowed_origins** (str or list) - Optional - Allowed origins for CORS. - **logger** (bool) - Optional - Enable server logging. - **engineio_logger** (bool) - Optional - Enable Engine.IO logging. - **ping_interval** (int) - Optional - Interval in seconds for sending pings. - **ping_timeout** (int) - Optional - Timeout in seconds for receiving pings. #### Asyncio Server (`socketio.AsyncServer`) - **async_mode** (str) - Optional - 'asgi'. - **cors_allowed_origins** (list) - Optional - Allowed origins for CORS. - **max_http_buffer_size** (int) - Optional - Maximum size in bytes for HTTP buffer. ### Request Example ```python import socketio # Standard synchronous server sio = socketio.Server( async_mode='threading', cors_allowed_origins='*', logger=True, engineio_logger=True, ping_interval=25, ping_timeout=20 ) # Asyncio server sio_async = socketio.AsyncServer( async_mode='asgi', cors_allowed_origins=['http://localhost:3000', 'https://myapp.com'], max_http_buffer_size=1000000 ) ``` ### Response N/A (This is a constructor call) ### Response Example N/A ``` -------------------------------- ### Asyncio Python Socket.IO Class-Based Namespace Example Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Illustrates a class-based namespace for asyncio-based Python Socket.IO servers. It uses `socketio.AsyncNamespace` and defines event handlers as asynchronous coroutines. The example shows how to emit responses asynchronously. ```python class MyCustomNamespace(socketio.AsyncNamespace): def on_connect(self, sid, environ): pass def on_disconnect(self, sid, reason): pass async def on_my_event(self, sid, data): await self.emit('my_response', data) sio.register_namespace(MyCustomNamespace('/test')) ``` -------------------------------- ### Get Environ Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Retrieves the WSGI environ dictionary for a specific client session. ```APIDOC ## get_environ(sid, namespace=None) ### Description Returns the WSGI environ dictionary associated with a client's session. ### Method Function ### Endpoint N/A (This is a method call on the server object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sid** (string) - Required - The session ID of the client. - **namespace** (string) - Optional - The Socket.IO namespace. Defaults to the main namespace. ### Request Example ```python # Get the WSGI environ for client 'client1' environ_data = sio.get_environ('client1') print(environ_data.get('REMOTE_ADDR')) ``` ### Response #### Success Response (200) - **environ** (dict) - The WSGI environ dictionary for the client. ``` -------------------------------- ### Simple Clients Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api.md Documentation for SimpleClient and AsyncSimpleClient, used for basic SocketIO client interactions. ```APIDOC ## Simple Clients ### Description Provides documentation for `SimpleClient` and `AsyncSimpleClient`, which are designed for straightforward client-side communication with SocketIO servers. ### Endpoints This section details the methods and properties available for `SimpleClient` and `AsyncSimpleClient`. #### `socketio.SimpleClient` * **`connect(url, **kwargs)`**: Connects the client to the specified URL. * **`disconnect()`**: Disconnects the client from the server. * **`emit(event, data, namespace)`**: Emits an event to the server. * **`on(event, handler, namespace)`**: Registers an event handler. #### `socketio.AsyncSimpleClient` * **`connect(url, **kwargs)`**: Asynchronously connects the client to the specified URL. * **`disconnect()`**: Asynchronously disconnects the client from the server. * **`emit(event, data, namespace)`**: Asynchronously emits an event to the server. * **`on(event, handler, namespace)`**: Asynchronously registers an event handler. ``` -------------------------------- ### Initialize AsyncServer with Default Settings (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Instantiates the `AsyncServer` class with default configurations. This server is built for asyncio and supports websocket and long-polling. It uses in-memory client management and asynchronous event handlers by default. ```python import socketio sio = socketio.AsyncServer() ``` -------------------------------- ### Get Environment Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Retrieves the WSGI environ dictionary for a specific client session. ```APIDOC ## GET /socket.io/environ ### Description Retrieves the WSGI environ dictionary for a specific client session. ### Method GET ### Endpoint /socket.io/ ### Parameters #### Query Parameters - **sid** (string) - Required - The session ID of the client. - **namespace** (string) - Optional - The Socket.IO namespace. Defaults to the main namespace. ### Response #### Success Response (200) - **environ** (dict) - The WSGI environment dictionary for the client. #### Response Example ```json { "environ": { "HTTP_HOST": "localhost:5000", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SERVER_NAME": "localhost", "SERVER_PORT": "5000", "wsgi.input": "", "wsgi.url_scheme": "http" } } ``` ``` -------------------------------- ### Get Session Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Retrieves the user session data associated with a client's session ID. ```APIDOC ## GET /socket.io/session ### Description Retrieves the user session data associated with a client's session ID. ### Method GET ### Endpoint /socket.io/ ### Parameters #### Query Parameters - **sid** (string) - Required - The session ID of the client. - **namespace** (string) - Optional - The Socket.IO namespace. Defaults to the main namespace. ### Response #### Success Response (200) - **session** (dict) - The user session dictionary for the client. #### Response Example ```json { "session": { "username": "testuser", "user_id": 123 } } ``` ### Notes Modifications to the returned session dictionary are not guaranteed to be preserved unless `save_session()` is called or the `session` context manager is used. ``` -------------------------------- ### Create Python Socket.IO Client Instance Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/client.md Demonstrates the creation of Socket.IO client instances for both standard Python and `asyncio` environments. This involves instantiating `socketio.Client` for synchronous operations and `socketio.AsyncClient` for asynchronous operations. ```python import socketio # Standard Python client instance sio_client = socketio.Client() # Asyncio client instance sio_async_client = socketio.AsyncClient() ``` -------------------------------- ### Create Simple Socket.IO Client Instance (Python and Asyncio) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/client.md Demonstrates creating instances of the Socket.IO simple client using context managers for both standard Python and asyncio applications. The context manager ensures proper disconnection. ```python import socketio # standard Python with socketio.SimpleClient() as sio: # ... connect to a server and use the client # ... no need to manually disconnect! # asyncio async with socketio.AsyncSimpleClient() as sio: # ... connect to a server and use the client # ... no need to manually disconnect! ``` -------------------------------- ### Get Session Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Retrieves the user session data for a client. Modifications to the returned dictionary are not guaranteed to be preserved. ```APIDOC ## async get_session(sid, namespace=None) ### Description Retrieves the user session dictionary for a given client session ID. ### Method Asynchronous Function (Coroutine) ### Endpoint N/A (This is a method call on the server object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sid** (string) - Required - The session ID of the client. - **namespace** (string) - Optional - The Socket.IO namespace. Defaults to the main namespace. ### Request Example ```python # Get the session for client 'client1' session_data = await sio.get_session('client1') print(session_data) ``` ### Response #### Success Response (200) - **session** (dict) - The user session data associated with the client. Modifications may not be persisted. ``` -------------------------------- ### Manually Instantiate Simple Socket.IO Client (Python and Asyncio) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/client.md Shows how to manually create instances of the Socket.IO simple client for both standard Python and asyncio applications without using a context manager. ```python import socketio # standard Python sio = socketio.SimpleClient() # asyncio sio = socketio.AsyncSimpleClient() ``` -------------------------------- ### KafkaManager: Get Active Namespaces Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_manager.md Returns an iterable containing the names of all currently active namespaces. ```python kafka_manager.get_namespaces() ``` -------------------------------- ### Create Socket.IO Server Instance (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Demonstrates how to create a standard Socket.IO server instance using the `socketio.Server` class. This server is compatible with the Python standard library. ```python import socketio # create a Socket.IO server sio = socketio.Server() ``` -------------------------------- ### KafkaManager: Get Client Rooms Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_manager.md Returns an iterable of all rooms a specific client is currently in, within a given namespace. ```python kafka_manager.get_rooms(sid, namespace) ``` -------------------------------- ### Get Client Transport (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Returns the transport mechanism used by a client connection, either 'polling' or 'websocket'. This information can be useful for debugging or implementing transport-specific logic. ```python def 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. """ pass ``` -------------------------------- ### Get Socket ID for Namespace (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_client.md Retrieves the unique session ID (sid) associated with a specific Socket.IO namespace. If no namespace is provided, it defaults to the main namespace. ```python import socketio sio = socketio.AsyncClient() async def get_sid_example(): await sio.connect('http://localhost:5000') default_sid = sio.get_sid() print(f'Default namespace SID: {default_sid}') test_sid = sio.get_sid(namespace='/test') print(f'/test namespace SID: {test_sid}') # Example of calling the async function # import asyncio # asyncio.run(get_sid_example()) ``` -------------------------------- ### Get Client Environ Dictionary (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Retrieves the WSGI environ dictionary for a specific client session. This provides access to request-specific information. The namespace can be specified if not using the default. ```python def get_environ(self, sid, namespace=None): """ Return the WSGI environ dictionary for a client. Parameters: sid (str): The session of the client. namespace (str): The Socket.IO namespace. Defaults to the default namespace. """ pass ``` -------------------------------- ### Get Client Environment - Python Socket.IO Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Retrieves the WSGI environ dictionary for a given client session ID. Useful for accessing request-specific information. Supports specifying a namespace. ```python environ = server.get_environ(sid='client_sid', namespace='/custom') ``` -------------------------------- ### Retrieving Socket.IO Information in Python Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_manager.md Provides methods to retrieve information about active namespaces, rooms, and participants. Note that in multi-server setups, `get_participants` only returns local participants. ```python server.get_namespaces() server.get_participants(namespace, room) server.get_rooms(sid, namespace) ``` -------------------------------- ### Get Client Session (Python) Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/api_server.md Asynchronously retrieves the user session dictionary for a client. Modifications to the returned dictionary are not guaranteed to be preserved; use the session context manager for reliable updates. The namespace can be specified. ```python async def get_session(self, sid, namespace=None): """ Return the user session for a client. Parameters: sid (str): The session id of the client. namespace (str): The Socket.IO namespace. Defaults to the default namespace. Returns: dict: The user session dictionary. """ pass ``` -------------------------------- ### Gevent with uWSGI Source: https://github.com/miguelgrinberg/python-socketio/blob/main/docs/server.md Configuration hint for using Socket.IO with Gevent and uWSGI. When both are installed and eventlet is not, Socket.IO will automatically use uWSGI's native WebSocket support for asynchronous operations. ```python sio = socketio.Server(async_mode='gevent') # Explicitly requesting gevent mode ```