### Run JavaScript Server
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/server/javascript/README.md
Execute this command to start the Node.js server for the eio-latency example.
```bash
node index
```
--------------------------------
### Install Engine.IO Async Client
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Install the asyncio-compatible client. Use this command if you plan to use the `asyncio` client.
```bash
pip install "python-engineio[asyncio_client]"
```
--------------------------------
### Install Engine.IO Client
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Install the standard Python client with its dependencies. Use this command for the regular Python client.
```bash
pip install "python-engineio[client]"
```
--------------------------------
### Install Dependencies
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/client/javascript/README.md
Run this command in your terminal to install the necessary Node.js packages for the client.
```bash
npm install
```
--------------------------------
### Asyncio ASGI Server Setup
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Configure an Engine.IO server for asyncio-based ASGI applications. Static file serving is intended for development only.
```python
import engineio
eio = engineio.AsyncServer()
app = engineio.ASGIApp(eio, static_files=static_files)
```
--------------------------------
### Configure Engine.IO with Eventlet
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate Server with async_mode='eventlet' for explicit Eventlet integration. Ensure the library is installed.
```python
eio = engineio.Server(async_mode='eventlet')
```
--------------------------------
### Install Python Engine.IO Server
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Use this command to install the Python Engine.IO server package.
```bash
pip install "python-engineio"
```
--------------------------------
### Run Tornado Application
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Start the Tornado application by listening on a port and running the IOLoop. This setup supports coexistence with the Engine.IO server.
```python
app.listen(port)
tornado.ioloop.IOLoop.current().start()
```
--------------------------------
### Configure Engine.IO with aiohttp
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate AsyncServer with async_mode='aiohttp' for explicit aiohttp integration. Ensure the library is installed.
```python
eio = engineio.AsyncServer(async_mode='aiohttp')
```
--------------------------------
### Launch uWSGI Server with Gevent and WebSockets
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Start a uWSGI server with gevent support, enabling native WebSocket connections. Ensure uWSGI is compiled with WebSocket and SSL support.
```bash
$ uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file latency.py --callable app
```
--------------------------------
### Start Custom Background Task (Standard)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Starts a custom background task. The arguments passed are the function to execute and any positional or keyword arguments for that function. This function does not wait for the background task to complete.
```python
def my_background_task(my_argument)
# do some background work here!
pass
eio.start_background_task(my_background_task, 123)
```
--------------------------------
### Initialize Engine.IO Server with Gevent
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate an Engine.IO server, explicitly requesting the 'gevent' asynchronous mode. This requires the gevent library to be installed.
```python
eio = engineio.Server(async_mode='gevent')
```
--------------------------------
### Run Latency Client
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/client/javascript/README.md
Execute this command to start the JavaScript client. It will attempt to connect to a server on localhost:5000, or a different port if the PORT environment variable is set.
```bash
node latency_client
```
--------------------------------
### Start Engine.IO App with Gunicorn
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Use this command to start an Engine.IO application with Gunicorn, specifying the number of worker processes and threads. The `--threads` option determines the maximum number of concurrent clients the server can handle.
```bash
gunicorn -w 1 --threads 100 module:app
```
--------------------------------
### Start a Background Task
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
The start_background_task() helper function allows you to run custom functions in the background. Pass the function and its arguments.
```python
def my_background_task(my_argument):
# do some background work here!
pass
eio.start_background_task(my_background_task, 123)
```
```python
async def my_background_task(my_argument):
# do some background work here!
pass
eio.start_background_task(my_background_task, 123)
```
--------------------------------
### Start Custom Background Task (Asyncio)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Starts a custom background task in an asyncio application. The arguments passed are the coroutine function to execute and any positional or keyword arguments for that function. This function does not wait for the background task to complete.
```python
async def my_background_task(my_argument)
# do some background work here!
pass
eio.start_background_task(my_background_task, 123)
```
--------------------------------
### Python Engine.IO Client Example
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/intro.md
A basic Python client that connects to an Engine.IO server, handles connect, message, and disconnect events, and sends a response.
```python
import engineio
eio = engineio.Client()
@eio.on('connect')
def on_connect():
print('connection established')
@eio.on('message')
def on_message(data):
print('message received with ', data)
eio.send({'response': 'my response'})
@eio.on('disconnect')
def on_disconnect():
print('disconnected from server')
eio.connect('http://localhost:5000')
eio.wait()
```
--------------------------------
### Python Eventlet Server Example
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/intro.md
A basic Engine.IO server using Eventlet for asynchronous handling. It sets up a WSGI application and defines handlers for connect, message, and disconnect events.
```python
import engineio
import eventlet
eio = engineio.Server()
app = engineio.WSGIApp(eio, static_files={
'/': {'content_type': 'text/html', 'filename': 'index.html'}
})
@eio.on('connect')
def connect(sid, environ):
print("connect ", sid)
@eio.on('message')
def message(sid, data):
print("message ", data)
eio.send(sid, 'reply')
@eio.on('disconnect')
def disconnect(sid):
print('disconnect ', sid)
if __name__ == '__main__':
eventlet.wsgi.server(eventlet.listen(('', 5000)), app)
```
--------------------------------
### Initialize Engine.IO Server with Gevent and uWSGI
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate an Engine.IO server, explicitly requesting the 'gevent_uwsgi' asynchronous mode. This leverages uWSGI's native WebSocket support and requires both gevent and uWSGI to be installed.
```python
# gevent with uWSGI
eio = engineio.Server(async_mode='gevent_uwsgi')
```
--------------------------------
### Python Asyncio Uvicorn Server Example
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/intro.md
A basic Engine.IO server using asyncio and Uvicorn for asynchronous handling. It sets up an ASGI application and defines handlers for connect, message, and disconnect events.
```python
import engineio
import uvicorn
eio = engineio.AsyncServer()
app = engineio.ASGIApp(eio, static_files={
'/': {'content_type': 'text/html', 'filename': 'index.html'}
})
@eio.on('connect')
def connect(sid, environ):
print("connect ", sid)
@eio.on('message')
async def message(sid, data):
print("message ", data)
await eio.send(sid, 'reply')
@eio.on('disconnect')
def disconnect(sid):
print('disconnect ', sid)
if __name__ == '__main__':
uvicorn.run('127.0.0.1', 5000)
```
--------------------------------
### JavaScript Engine.IO Client Example
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/intro.md
A basic JavaScript client that connects to an Engine.IO server, handles open, message, and close events, and sends a response.
```javascript
```
--------------------------------
### Deploy Eventlet Server as WSGI Application
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Wrap the Engine.IO server instance with engineio.WSGIApp and start it using eventlet.wsgi.server. This enables long-polling and WebSocket transports.
```python
app = engineio.WSGIApp(eio)
import eventlet
eventlet.wsgi.server(eventlet.listen(('', 8000)), app)
```
--------------------------------
### Save and Get User Session Data
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Use save_session() and get_session() to store and retrieve application-specific data for each connected client. This data persists for the life of the connection.
```python
import engineio
eio = engineio.Server()
@eio.on('connect')
def on_connect(sid, environ):
username = authenticate_user(environ)
eio.save_session(sid, {'username': username})
@eio.on('message')
def on_message(sid, data):
session = eio.get_session(sid)
print('message from ', session['username'])
```
```python
import engineio
eio = engineio.AsyncServer()
@eio.on('connect')
async def on_connect(sid, environ):
username = authenticate_user(environ)
await eio.save_session(sid, {'username': username})
@eio.on('message')
async def on_message(sid, data):
session = await eio.get_session(sid)
print('message from ', session['username'])
```
--------------------------------
### Get Client Session ID
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Access the unique session identifier assigned by the server after a successful connection. This is stored in the `sid` attribute.
```python
print('my sid is', eio.sid)
```
--------------------------------
### Create Standard Engine.IO Server Instance
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate a standard Engine.IO server and wrap it with a WSGI application.
```python
import engineio
# create a Engine.IO server
eio = engineio.Server()
# wrap with a WSGI application
app = engineio.WSGIApp(eio)
```
--------------------------------
### Initialize WSGIApp with Static Files
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Pass the static file configuration dictionary to the WSGIApp constructor when initializing the Engine.IO server.
```python
# for standard WSGI applications
eio = engineio.Server()
app = engineio.WSGIApp(eio, static_files=static_files)
```
--------------------------------
### Client Instantiation
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Instantiate either the standard Python client or the asyncio client.
```APIDOC
## Client Instantiation
To instantiate an Engine.IO client, simply create an instance of the appropriate client class:
```python
import engineio
# standard Python
eio = engineio.Client()
# asyncio
eio = engineio.AsyncClient()
```
```
--------------------------------
### Instantiate Engine.IO Client
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Create an instance of the appropriate client class. Choose between the standard Python client or the asyncio client.
```python
import engineio
# standard Python
eio = engineio.Client()
# asyncio
eio = engineio.AsyncClient()
```
--------------------------------
### Configure Serving Entire Directory
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Map a URL prefix to a local directory to serve all files within it as static assets.
```python
static_files = {
'/static': './public',
}
```
--------------------------------
### Create Asyncio Engine.IO Server Instance
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate an asyncio-compatible Engine.IO server and wrap it with an ASGI application.
```python
# create a Engine.IO server
eio = engineio.AsyncServer()
# wrap with ASGI application
app = engineio.ASGIApp(eio)
```
--------------------------------
### Configure Engine.IO with Tornado
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate AsyncServer with async_mode='tornado' for explicit Tornado integration. Tornado version 5+ is required.
```python
eio = engineio.AsyncServer(async_mode='tornado')
```
--------------------------------
### Initialize Engine.IO Server with Threading
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate an Engine.IO server, explicitly requesting the 'threading' asynchronous mode. This is suitable for development servers like Werkzeug.
```python
eio = engineio.Server(async_mode='threading')
```
--------------------------------
### Configure Engine.IO with Sanic
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Instantiate AsyncServer with async_mode='sanic' for explicit Sanic integration. Consider using ASGI integration for recent Sanic versions.
```python
eio = engineio.AsyncServer(async_mode='sanic')
```
--------------------------------
### Connecting to a Server
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Establish a connection to an Engine.IO server using the `connect()` method.
```APIDOC
## Connecting to a Server
The connection to a server is established by calling the `connect()` method:
```python
eio.connect('http://localhost:5000')
```
In the case of the `asyncio` client, the method is a coroutine:
```python
await eio.connect('http://localhost:5000')
```
Upon connection, the server assigns the client a unique session identifier. The application can find this identifier in the `sid` attribute:
```python
print('my sid is', eio.sid)
```
```
--------------------------------
### Configure Static File Mapping
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Define a dictionary to map URL paths to local static files for the Engine.IO server.
```python
static_files = {
'/': 'latency.html',
'/static/engine.io.js': 'static/engine.io.js',
'/static/style.css': 'static/style.css',
}
```
--------------------------------
### Create ASGI Application
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Use engineio.ASGIApp to create an ASGI-compatible application that forwards Engine.IO traffic to an AsyncServer instance. It can also forward other traffic to a different ASGI app.
```python
import engineio
eio = engineio.AsyncServer(async_mode='asgi')
app = engineio.ASGIApp(eio)
```
```python
import engineio
eio = engineio.AsyncServer(async_mode='asgi')
app = engineio.ASGIApp(eio, other_app)
```
--------------------------------
### Connect to Engine.IO Server
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Establish a connection to the Engine.IO server. For the asyncio client, this method must be awaited.
```python
eio.connect('http://localhost:5000')
```
```python
await eio.connect('http://localhost:5000')
```
--------------------------------
### Enable Client Logging (Standard Python)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Enables log output to stderr at the INFO level for debugging. Ensure the 'engineio' library is imported.
```python
import engineio
# standard Python
eio = engineio.Client(logger=True)
```
--------------------------------
### Launch Eventlet with Gunicorn
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Use this command to launch an Engine.IO application with Eventlet via Gunicorn. Gunicorn requires a single worker process for Eventlet.
```bash
$ gunicorn -k eventlet -w 1 module:app
```
--------------------------------
### Configure Default Index File with Content Type
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Specify a default filename and a non-standard content type for slash-ending URL requests.
```python
static_files = {
'/static': './public',
'': {'filename': 'image.gif', 'content_type': 'text/plain'},
}
```
--------------------------------
### Run aiohttp Application
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Execute the aiohttp application using web.run_app(). This allows regular routes to coexist with the Engine.IO server.
```python
if __name__ == '__main__':
web.run_app(app)
```
--------------------------------
### Enable Client Logging (Asyncio)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Enables log output to stderr at the INFO level for debugging in asyncio applications. Ensure the 'engineio' library is imported.
```python
import engineio
# asyncio
eio = engineio.AsyncClient(logger=True)
```
--------------------------------
### Attach aiohttp Server to Application
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Attach the configured Engine.IO server instance to an existing aiohttp web application.
```python
app = web.Application()
eio.attach(app)
```
--------------------------------
### Configure Default Index File for Directory
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Set a default filename to be served when a URL ending in a slash is requested from a directory mapping.
```python
static_files = {
'/static': './public',
'': 'image.gif',
}
```
--------------------------------
### Deploy Threading Server with Flask
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Deploy an Engine.IO application configured for threading alongside a Flask application using Flask's development server.
```python
eio = engineio.Server(async_mode='threading')
app = Flask(__name__)
app.wsgi_app = engineio.WSGIApp(eio, app.wsgi_app)
```
--------------------------------
### Simple Engine.IO Client
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/server/aiohttp/simple.html
This JavaScript code snippet shows a basic client implementation for Engine.IO. It connects to a server, logs connection status, receives messages, and sends a message periodically. Ensure the server is running and accessible at the specified address.
```javascript
$(document).ready(function() { var socket = eio('http://' + document.domain + ':' + location.port); socket.on('open', function() { $('#log').append("Connected to server.
"); }); socket.on('message', function(data) { $('#log').append("Server says: " + data + "
"); }); socket.on('close', function() { $('#log').append("Server closed the connection.
"); }); window.setInterval(function() { $('#log').append("Sending message to server...
"); socket.send('hello from client side!'); }, 5000); });
```
--------------------------------
### Launch Gevent with Gunicorn
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Use this command to launch an Engine.IO application with Gevent via Gunicorn. Gunicorn requires a single worker process for Gevent.
```bash
$ gunicorn -k gevent -w 1 module:app
```
--------------------------------
### Handle Disconnect Reasons
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Implement specific logic for different disconnect reasons. Use the `eio.reason` constants to differentiate between client-initiated, server-initiated, or accidental disconnects.
```python
@eio.on('disconnect')
def on_disconnect(reason):
if reason == eio.reason.CLIENT_DISCONNECT:
print('client disconnection')
elif reason == eio.reason.SERVER_DISCONNECT:
print('the server kicked me out')
else:
print(f'disconnect reason: {reason}')
```
--------------------------------
### Enable Server Logging
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Configure the Engine.IO server to output logs to the terminal for debugging. Set logger=True for INFO level or logger=False for ERROR level.
```python
import engineio
# standard Python
eio = engineio.Server(logger=True)
```
```python
import engineio
# asyncio
eio = engineio.AsyncServer(logger=True)
```
--------------------------------
### Deploy Gevent Server with WSGI
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Deploy a Gevent-configured Engine.IO server as a standard WSGI application using gevent's WSGI server.
```python
from gevent import pywsgi
app = engineio.WSGIApp(eio)
pywsgi.WSGIServer(('', 8000), app).serve_forever()
```
--------------------------------
### Integrate Tornado Handler with Application
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Include the Engine.IO handler in the Tornado application's route list using get_tornado_handler(eio).
```python
app = tornado.web.Application(
[
(r"/engine.io/", engineio.get_tornado_handler(eio)),
],
# ... other application options
)
```
--------------------------------
### Attach Sanic Server to Application
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Attach the configured Engine.IO server instance to an existing Sanic application.
```python
app = Sanic()
eio.attach(app)
```
--------------------------------
### Configure Static File with Explicit Content Type
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Specify a custom content type for a static file mapping.
```python
static_files = {
'/': {'filename': 'latency.html', 'content_type': 'text/plain'},
}
```
--------------------------------
### Send Message to Client (Asynchronous)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Send a message to a specific client asynchronously using await eio.send(). This is used in asyncio environments.
```python
await eio.send(sid, {'foo': 'bar'})
```
--------------------------------
### Manage User Session with Context Manager
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
The session() context manager provides a convenient way to access and modify user session data. For asyncio servers, use the asynchronous context manager.
```python
import engineio
eio = engineio.Server()
@eio.on('connect')
def on_connect(sid, environ):
username = authenticate_user(environ)
with eio.session(sid) as session:
session['username'] = username
@eio.on('message')
def on_message(sid, data):
with eio.session(sid) as session:
print('message from ', session['username'])
```
```python
import engineio
eio = engineio.AsyncServer()
@eio.on('connect')
def on_connect(sid, environ):
username = authenticate_user(environ)
async with eio.session(sid) as session:
session['username'] = username
@eio.on('message')
def on_message(sid, data):
async with eio.session(sid) as session:
print('message from ', session['username'])
```
--------------------------------
### Run Sanic Application
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Execute the Sanic application using app.run(). This allows regular routes to coexist with the Engine.IO server.
```python
if __name__ == '__main__':
app.run()
```
--------------------------------
### Client-side EIO Latency Measurement
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/server/aiohttp/latency.html
Connects to an Engine.IO server, sends 'ping' messages periodically, and displays the latency. Requires an HTML structure with 'chart' and 'latency' elements.
```javascript
var socket = eio('http://' + document.domain + ':' + location.port);
var char = $("#chart").get(0);
socket.on('open', function() {
if (chart.getContext) {
render();
window.onresize = render;
}
send();
});
socket.on('message', function(data) {
var latency = new Date - last;
$('#latency').text(latency + 'ms');
if (time) time.append(+new Date, latency);
setTimeout(send, 100);
});
socket.on('close', function() {
if (smoothie) smoothie.stop();
$('#transport').text('(disconnected)');
});
var last;
function send() {
last = new Date;
socket.send('ping');
$('#transport').text(socket.transport.name);
}
// chart
var smoothie;
var time;
function render() {
if (smoothie) smoothie.stop();
chart.width = document.body.clientWidth;
smoothie = new SmoothieChart();
smoothie.streamTo(chart, 1000);
time = new TimeSeries();
smoothie.addTimeSeries(time, {
strokeStyle: 'rgb(255, 0, 0)',
fillStyle: 'rgba(255, 0, 0, 0.4)',
lineWidth: 2
});
}
```
--------------------------------
### EIO Client Connection and Latency Measurement
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/server/sanic/latency.html
Connects to an EIO server, measures latency by sending 'ping' messages, and updates the UI with the current transport and latency. Requires chart rendering libraries.
```javascript
var socket = eio('http://' + document.domain + ':' + location.port);
var char = $("#chart").get(0);
socket.on('open', function() {
if (chart.getContext) {
render();
window.onresize = render;
}
send();
});
socket.on('message', function(data) {
var latency = new Date - last;
$('#latency').text(latency + 'ms');
if (time) time.append(+new Date, latency);
setTimeout(send, 100);
});
socket.on('close', function() {
if (smoothie) smoothie.stop();
$('#transport').text('(disconnected)');
});
var last;
function send() {
last = new Date;
socket.send('ping');
$('#transport').text(socket.transport.name);
}
// chart
var smoothie;
var time;
function render() {
if (smoothie) smoothie.stop();
chart.width = document.body.clientWidth;
smoothie = new SmoothieChart();
smoothie.streamTo(chart, 1000);
time = new TimeSeries();
smoothie.addTimeSeries(time, {
strokeStyle: 'rgb(255, 0, 0)',
fillStyle: 'rgba(255, 0, 0, 0.4)',
lineWidth: 2
});
}
```
--------------------------------
### Configure Sanic Server for CORS
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Initialize the Engine.IO server with cors_allowed_origins=[] to disable its CORS support and let Sanic manage it. This is necessary for compatibility with sanic-cors.
```python
eio = engineio.AsyncServer(async_mode='sanic', cors_allowed_origins=[])
```
--------------------------------
### Integrate Engine.IO as WSGI Middleware
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Wrap an existing WSGI application with Engine.IO to act as middleware, forwarding non-Engine.IO traffic.
```python
from wsgi import app # a Flask, Django, etc. application
app = engineio.WSGIApp(eio, app)
```
--------------------------------
### Define Connect Event Handler
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Define a handler for the 'connect' event using the @eio.on decorator. The return value determines if the connection is accepted.
```python
@eio.on('connect')
def on_connect(sid):
print('A client connected!')
```
--------------------------------
### Handle Specific Disconnect Reasons
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Handle different disconnect reasons within the 'disconnect' event handler. Use eio.reason constants for specific checks.
```python
@eio.on('disconnect')
def on_disconnect(sid, reason):
if reason == eio.reason.CLIENT_DISCONNECT:
print('the client went away')
elif reason == eio.reason.SERVER_DISCONNECT:
print('the client was kicked out')
else:
print(f'disconnect reason: {reason}')
```
--------------------------------
### Send Message to Client (Synchronous)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Send a message to a specific client using the send() method. The data can be a string, bytes, dictionary, or list.
```python
eio.send(sid, {'foo': 'bar'})
```
--------------------------------
### Defining Event Handlers
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Define event handlers using the `@eio.on()` decorator to respond to connection events.
```APIDOC
## Defining Event Handlers
To respond to events triggered by the connection or the server, event handler functions must be defined using the `on` decorator:
```python
@eio.on('connect')
def on_connect():
print('I\'m connected!')
@eio.on('message')
def on_message(data):
print('I received a message!')
@eio.on('disconnect')
def on_disconnect(reason):
print('I\'m disconnected! reason:', reason)
```
For the `asyncio` server, event handlers can be regular functions as above, or can also be coroutines:
```python
@eio.on('message')
async def on_message(data):
print('I received a message!')
```
The argument given to the `on` decorator is the event name. The events that are supported are `connect`, `message` and `disconnect`.
The `data` argument passed to the `'message'` event handler contains application-specific data provided by the server with the event.
The `disconnect` handler is invoked for client initiated disconnects, server initiated disconnects, or accidental disconnects, for example due to networking failures. The argument passed to this handler provides the disconnect reason. Example:
```python
@eio.on('disconnect')
def on_disconnect(reason):
if reason == eio.reason.CLIENT_DISCONNECT:
print('client disconnection')
elif reason == eio.reason.SERVER_DISCONNECT:
print('the server kicked me out')
else:
print(f'disconnect reason: {reason}')
```
```
--------------------------------
### Send Message with Engine.IO Client
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Send data to the server using the `send()` method. The data can be a string, bytes, dictionary, or list. For the asyncio client, this method must be awaited.
```python
eio.send({'foo': 'bar'})
```
```python
await eio.send({'foo': 'bar'})
```
--------------------------------
### Wait for Connection End (Standard)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Use this method when the main thread has nothing else to do and should simply wait for the client connection to terminate.
```python
eio.wait()
```
--------------------------------
### Client-side Engine.IO Latency Measurement
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/server/wsgi/templates/latency.html
This JavaScript code connects to the server using Engine.IO, listens for messages, and sends 'ping' messages to measure latency. It updates a display with the current latency and visualizes it on a chart. Requires the 'eio' library and DOM manipulation.
```javascript
// socket var socket = eio('http://' + document.domain + ':' + location.port);
var char = $("chart").get(0);
socket.on('open', function() {
if (chart.getContext) {
render();
window.onresize = render;
}
send();
});
socket.on('message', function(data) {
var latency = new Date - last;
$('#latency').text(latency + 'ms');
if (time) time.append(+new Date, latency);
setTimeout(send, 100);
});
socket.on('close', function() {
if (smoothie) smoothie.stop();
$('#transport').text('(disconnected)');
});
var last;
function send() {
last = new Date;
socket.send('ping');
$('#transport').text(socket.transport.name);
}
// chart
var smoothie;
var time;
function render() {
if (smoothie) smoothie.stop();
chart.width = document.body.clientWidth;
smoothie = new SmoothieChart();
smoothie.streamTo(chart, 1000);
time = new TimeSeries();
smoothie.addTimeSeries(time, {
strokeStyle: 'rgb(255, 0, 0)',
fillStyle: 'rgba(255, 0, 0, 0.4)',
lineWidth: 2
});
}
```
--------------------------------
### Client-side Latency Measurement with Engine.IO
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/server/asgi/latency.html
This JavaScript code connects to an Engine.IO server, sends 'ping' messages, and updates the displayed latency. It requires the 'eio' library and DOM manipulation for rendering.
```javascript
var socket = eio('http://' + document.domain + ':' + location.port);
var char = $(\'chart\').get(0);
socket.on('open', function() {
if (chart.getContext) {
render();
window.onresize = render;
}
send();
});
socket.on('message', function(data) {
var latency = new Date - last;
$(\'#latency\').text(latency + \'ms\');
if (time) time.append(+new Date, latency);
setTimeout(send, 100);
});
socket.on('close', function() {
if (smoothie) smoothie.stop();
$(\'#transport\').text(\' (disconnected)\' );
});
var last;
function send() {
last = new Date;
socket.send('ping');
$(\'#transport\').text(socket.transport.name);
}
var smoothie;
var time;
function render() {
if (smoothie) smoothie.stop();
chart.width = document.body.clientWidth;
smoothie = new SmoothieChart();
smoothie.streamTo(chart, 1000);
time = new TimeSeries();
smoothie.addTimeSeries(time, {
strokeStyle: \'rgb(255, 0, 0)\',
fillStyle: \'rgba(255, 0, 0, 0.4)\',
lineWidth: 2
});
}
```
--------------------------------
### Engine.IO Latency Measurement and Display
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/examples/server/tornado/templates/latency.html
This client-side JavaScript code connects to the server using Engine.IO, sends 'ping' messages, and updates a display with the measured latency. It also handles connection open, message, and close events.
```javascript
// socket var socket = eio('http://' + document.domain + ':' + location.port); var char = $('chart').get(0); socket.on('open', function() { if (chart.getContext) { render(); window.onresize = render; } send(); }); socket.on('message', function(data) { var latency = new Date - last; $('#latency').text(latency + 'ms'); if (time) time.append(+new Date, latency); setTimeout(send, 100); }); socket.on('close', function() { if (smoothie) smoothie.stop(); $('#transport').text('(disconnected)'); }); var last; function send() { last = new Date; socket.send('ping'); $('#transport').text(socket.transport.name); }
```
```javascript
// chart var smoothie; var time; function render() { if (smoothie) smoothie.stop(); chart.width = document.body.clientWidth; smoothie = new SmoothieChart(); smoothie.streamTo(chart, 1000); time = new TimeSeries(); smoothie.addTimeSeries(time, { strokeStyle: 'rgb(255, 0, 0)', fillStyle: 'rgba(255, 0, 0, 0.4)', lineWidth: 2 }); }
```
--------------------------------
### Enable CORS in Sanic
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Set the CORS_SUPPORTS_CREDENTIALS configuration option to True in the Sanic application to enable CORS support when using the sanic-cors extension.
```python
app.config['CORS_SUPPORTS_CREDENTIALS'] = True
```
--------------------------------
### Define Engine.IO Event Handlers
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Define event handler functions using the `@eio.on` decorator to respond to connection events. Handlers can be regular functions or coroutines for asyncio.
```python
@eio.on('connect')
def on_connect():
print('I\'m connected!')
@eio.on('message')
def on_message(data):
print('I received a message!')
@eio.on('disconnect')
def on_disconnect(reason):
print('I\'m disconnected! reason:', reason)
```
```python
@eio.on('message')
async def on_message(data):
print('I received a message!')
```
--------------------------------
### Sending Messages
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Send messages to the server using the `send()` method. Supports various data types.
```APIDOC
## Sending Messages
The client can send a message to the server using the `send()` method:
```python
eio.send({'foo': 'bar'})
```
Or in the case of `asyncio`, as a coroutine:
```python
await eio.send({'foo': 'bar'})
```
The single argument provided to the method is the data that is passed on to the server. The data can be of type `str`, `bytes`, `dict` or `list`. The data included inside dictionaries and lists is also constrained to these types.
The `send()` method can be invoked inside an event handler as a response to a server event, or in any other part of the application, including in background tasks.
```
--------------------------------
### Wait for Connection End (Asyncio)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Use this method in asyncio applications when the main coroutine has nothing else to do and should simply wait for the client connection to terminate.
```python
await eio.wait()
```
--------------------------------
### Define Async Message Event Handler
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Define an asynchronous handler for the 'message' event using the @eio.on decorator. This is suitable for asyncio servers.
```python
@eio.on('message')
async def on_message(sid, data):
print('I received a message!')
```
--------------------------------
### Define Disconnect Event Handler
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Define a handler for the 'disconnect' event. The 'reason' argument provides information about why the client disconnected.
```python
@eio.on('disconnect')
def on_disconnect(sid, reason):
print('Client disconnected! reason:', reason)
```
--------------------------------
### Disconnecting from the Server
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Gracefully disconnect from the Engine.IO server using the `disconnect()` method.
```APIDOC
## Disconnecting from the Server
At any time the client can request to be disconnected from the server by invoking the `disconnect()` method:
```python
eio.disconnect()
```
For the `asyncio` client this is a coroutine:
```python
await eio.disconnect()
```
```
--------------------------------
### Disconnect from Engine.IO Server
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
Request to disconnect from the server by invoking the `disconnect()` method. For the asyncio client, this method must be awaited.
```python
eio.disconnect()
```
```python
await eio.disconnect()
```
--------------------------------
### Define Message Event Handler
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Define a handler for the 'message' event. The 'data' argument contains application-specific data from the client.
```python
@eio.on('message')
def on_message(sid, data):
print('I received a message!')
```
--------------------------------
### Sleep for a Duration
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
The sleep() method pauses execution for a specified number of seconds, useful when working with background tasks. Use the await keyword for asyncio.
```python
eio.sleep(2)
```
```python
await eio.sleep(2)
```
--------------------------------
### Sleep for a Duration (Asyncio)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
A convenience coroutine function for asyncio applications working with background tasks, allowing the current coroutine to sleep for a specified number of seconds.
```python
await eio.sleep(2)
```
--------------------------------
### Disconnect a Client
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/server.md
Use the disconnect() method to forcibly disconnect a client from the server using its session ID (sid).
```python
eio.disconnect(sid)
```
```python
await eio.disconnect(sid)
```
--------------------------------
### Sleep for a Duration (Standard)
Source: https://github.com/miguelgrinberg/python-engineio/blob/main/docs/client.md
A convenience function for applications working with their own background tasks, allowing the current thread to sleep for a specified number of seconds.
```python
eio.sleep(2)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.