### Basic Flask-SocketIO Application Setup Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/README.md This example demonstrates the basic setup of a Flask application with Flask-SocketIO integration. It includes initializing the app, configuring a secret key, setting up the SocketIO instance, defining a root route, and handling a custom SocketIO event. Ensure 'index.html' is in your templates directory. The application is run using socketio.run(). ```python from flask import Flask, render_template from flask_socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @socketio.event def my_event(message): emit('my response', {'data': 'got it!'}) if __name__ == '__main__': socketio.run(app) ``` -------------------------------- ### Gunicorn with Gevent Worker Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Use this command to start a Gunicorn server with gevent workers. Ensure gevent is installed. ```bash gunicorn -k gevent -w 1 module:app ``` -------------------------------- ### Gunicorn with Eventlet Worker Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Use this command to start a Gunicorn server with eventlet workers for Flask-SocketIO. Ensure eventlet is installed. ```bash gunicorn --worker-class eventlet -w 1 module:app ``` -------------------------------- ### Install Flask-SocketIO using pip Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/intro.md Use this command to install the Flask-SocketIO package. Ensure you have pip installed and accessible in your environment. ```default pip install flask-socketio ``` -------------------------------- ### uWSGI Server with Gevent and WebSockets Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Starts a uWSGI server with gevent and native WebSocket support. Requires uWSGI to be compiled with WebSocket and SSL support. Adjust port and gevent worker count as needed. ```bash $ uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file app.py --callable app ``` -------------------------------- ### HTTP Session Management with AJAX Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/example/templates/sessions.html Handles session updates and retrieval via AJAX POST and GET requests. Ensure the server is configured to handle these requests. ```javascript window.setInterval(function() { $.ajax({ type: 'GET', url: '/session', success: function(data) { $('#http-session').text(data['session']); $('#http-user').text(data['user']); } }); }, 1000); ``` ```javascript $('#submit-http').click(function() { $.ajax({ type: 'POST', url: '/session', data: JSON.stringify({session: $('#http-session-set').val()}), contentType: 'application/json' }); }); ``` ```javascript $('#login-http').click(function() { $.ajax({ type: 'POST', url: '/session', data: JSON.stringify({user: $('#http-user-set').val()}), contentType: 'application/json' }); }); ``` ```javascript $('#logout-http').click(function() { $.ajax({ type: 'POST', url: '/session', data: JSON.stringify({user: null}), contentType: 'application/json' }); }); ``` -------------------------------- ### Gunicorn with Threaded Worker Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md For CPU-heavy applications or those incompatible with green threads, use Gunicorn's threaded worker with simple-websocket. Ensure simple-websocket is installed. ```bash gunicorn -w 1 --threads 100 module:app ``` -------------------------------- ### Gunicorn with GeventWebSocket Worker Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md This command is used when Gunicorn's gevent worker needs WebSocket support via gevent-websocket. Ensure gevent-websocket is installed. ```bash gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 module:app ``` -------------------------------- ### Basic Client-Side Socket.IO Connection Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Include this JavaScript in your HTML to load the Socket.IO client library and establish a connection to the server. It also sets up a listener for the 'connect' event and emits a test event. ```html ``` -------------------------------- ### Initialize Flask-SocketIO with init_app() Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md This pattern is useful for creating Flask applications within functions, allowing for deferred initialization of Flask-SocketIO. The socketio object is created globally and then attached to the app instance. ```python from flask import Flask, render_template from flask_socketio import SocketIO socketio = SocketIO() def create_app(): app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio.init_app(app) return app if __name__ == '__main__': app = create_app() socketio.run(app) ``` -------------------------------- ### Initialize Flask-SocketIO Directly Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use this method to add Flask-SocketIO to an existing Flask application. Ensure you have a SECRET_KEY configured. ```python from flask import Flask, render_template from flask_socketio import SocketIO app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) if __name__ == '__main__': socketio.run(app) ``` -------------------------------- ### Join and Leave Rooms Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use `join_room()` and `leave_room()` to manage user groups. Messages can then be sent to specific rooms using the `to` argument in `send()` or `emit()`. ```python from flask_socketio import join_room, leave_room, send @socketio.on('join') def on_join(data): username = data['username'] room = data['room'] join_room(room) send(username + ' has entered the room.', to=room) @socketio.on('leave') def on_leave(data): username = data['username'] room = data['room'] leave_room(room) send(username + ' has left the room.', to=room) ``` -------------------------------- ### Handle Connection Event Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Register a handler for the 'connect' event to perform actions when a client connects. An optional `auth` argument can be used for client authentication data. ```python from flask_socketio import emit @socketio.on('connect') def test_connect(auth): emit('my response', {'data': 'Connected'}) ``` -------------------------------- ### Configuring SocketIO with a Message Queue Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Initialize Flask-SocketIO with the `message_queue` argument to enable communication between multiple workers. The connection URL specifies the message queue service. ```python socketio = SocketIO(app, message_queue='redis://') ``` -------------------------------- ### Reject Connection Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Connections can be rejected by returning `False` or raising `ConnectionRefusedError` in the 'connect' handler. Arguments passed to the exception are returned to the client. ```python from flask_socketio import ConnectionRefusedError, emit @socketio.on('connect') def connect(): if not self.authenticate(request.args): raise ConnectionRefusedError('unauthorized!') ``` -------------------------------- ### Handle Custom Named Events with Multiple Arguments Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Create a handler for custom named events that accept multiple arguments. Ensure the client sends data matching these arguments. ```python from flask_socketio import SocketIO socketio = SocketIO() @socketio.on('my_event') def handle_my_custom_event(arg1, arg2, arg3): print('received args: ' + arg1 + arg2 + arg3) ``` -------------------------------- ### Broadcast Message from Server Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use `socketio.emit()` to broadcast messages to all clients when the server is the originator. `broadcast=True` is assumed when there is no client context. ```python from flask_socketio import SocketIO socketio = SocketIO() def some_function(): socketio.emit('some event', {'data': 42}) ``` -------------------------------- ### Compact Syntax for Custom Events Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use the `@socketio.event` decorator for a more concise way to define custom event handlers when the event name is a valid Python identifier. ```python from flask_socketio import SocketIO socketio = SocketIO() @socketio.event def my_custom_event(arg1, arg2, arg3): print('received args: ' + arg1 + arg2 + arg3) ``` -------------------------------- ### Send Named Events with Multiple Arguments Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md To send an event with multiple arguments using `emit()`, package the arguments as a tuple. The client will receive these as separate arguments in its callback. ```python from flask_socketio import emit, SocketIO socketio = SocketIO() @socketio.on('my event') def handle_my_custom_event(json): emit('my response', ('foo', 'bar', json), namespace='/chat') ``` -------------------------------- ### Send Unnamed String Messages Back to Client Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use the `send()` function to echo received string messages back to the client that sent them. This is suitable for simple text responses. ```python from flask_socketio import send, SocketIO socketio = SocketIO() @socketio.on('message') def handle_message(message): send(message) ``` -------------------------------- ### Send Named Events Back to Client Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Employ the `emit()` function to send named events and their data back to the client. This is more flexible than `send()` for custom event types. ```python from flask_socketio import emit, SocketIO socketio = SocketIO() @socketio.on('my event') def handle_my_custom_event(json): emit('my response', json) ``` -------------------------------- ### Register Event Handler with on_event Method Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use the `on_event` method to register an event handler when the decorator syntax is not convenient. This allows for dynamic handler registration. ```python from flask_socketio import SocketIO socketio = SocketIO() def my_function_handler(data): pass socketio.on_event('my event', my_function_handler, namespace='/test') ``` -------------------------------- ### Implement Class-Based Namespaces in Flask-SocketIO Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use `flask_socketio.Namespace` to create class-based namespaces for organizing event handlers. Events are mapped to methods prefixed with `on_`. ```python from flask_socketio import Namespace, emit class MyCustomNamespace(Namespace): def on_connect(self): pass def on_disconnect(self, reason): pass def on_my_event(self, data): emit('my_response', data) socketio.on_namespace(MyCustomNamespace('/test')) ``` -------------------------------- ### Nginx Load Balancing for Multiple Socket.IO Servers Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Configure Nginx for load balancing across multiple Socket.IO servers. The `ip_hash` directive ensures sticky sessions, directing a client to the same server. ```nginx upstream socketio_nodes { ip_hash; server 127.0.0.1:5000; server 127.0.0.1:5001; server 127.0.0.1:5002; # to scale the app, just add more nodes here! } server { listen 80; server_name _; location / { include proxy_params; proxy_pass http://127.0.0.1:5000; } location /static/ { alias /static/; expires 30d; } location /socket.io { include proxy_params; proxy_http_version 1.1; proxy_buffering off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_pass http://socketio_nodes/socket.io; } } ``` -------------------------------- ### Enable Logging in Flask-SocketIO Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Configure `SocketIO` with `logger=True` and `engineio_logger=True` to output protocol and transport logs to the terminal for debugging. ```python socketio = SocketIO(logger=True, engineio_logger=True) ``` -------------------------------- ### Send Messages to a Specific Namespace Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md When working with namespaces, `send()` and `emit()` use the incoming message's namespace by default. Specify a different namespace using the `namespace` argument to direct messages. ```python from flask_socketio import send, emit, SocketIO socketio = SocketIO() @socketio.on('message') def handle_message(message): send(message, namespace='/chat') @socketio.on('my event') def handle_my_custom_event(json): emit('my response', json, namespace='/chat') ``` -------------------------------- ### Send Events with Acknowledgement Callback Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use the `callback` argument in `emit()` to specify a server-side function that will be invoked when the client acknowledges receipt of the message. This confirms message delivery. ```python from flask_socketio import emit, SocketIO socketio = SocketIO() def ack(): print('message was received!') @socketio.on('my event') def handle_my_custom_event(json): emit('my response', json, callback=ack) ``` -------------------------------- ### Socket.IO Connection and Session Management Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/example/templates/sessions.html Manages Socket.IO connections, listens for session refresh events, and emits session update requests. Ensure Socket.IO client is loaded. ```javascript var socket = null; $('#connect').click(function() { if (!socket) { socket = io(); socket.on('refresh-session', function(data) { $('#socketio-session').text(data['session']); $('#socketio-user').text(data['user']); }); $('#connect').text('Disconnect'); $('#socketio').show(); } else { socket.disconnect(); socket = null; $('#socketio').hide(); $('#connect').text('Connect'); $('#socketio-session').text(''); $('#socketio-user').text(''); } }); ``` ```javascript window.setInterval(function() { if (socket) socket.emit('get-session'); }, 1000); ``` ```javascript $('#submit-socketio').click(function() { socket.emit('set-session', {session: $('#socketio-session-set').val()}); }); ``` ```javascript $('#login-socketio').click(function() { socket.emit('set-session', {user: $('#socketio-user-set').val()}); }); ``` ```javascript $('#logout-socketio').click(function() { socket.emit('set-session', {user: null}); }); ``` -------------------------------- ### Handle Unnamed String Messages Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Register a server-side handler for incoming string messages. This is useful for simple text-based communication. ```python from flask_socketio import SocketIO socketio = SocketIO() @socketio.on('message') def handle_message(data): print('received message: ' + data) ``` -------------------------------- ### Send Unnamed JSON Messages Back to Client Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Utilize the `send()` function with `json=True` to send JSON data back to the client. This ensures the data is correctly formatted and interpreted as JSON. ```python from flask_socketio import send, SocketIO socketio = SocketIO() @socketio.on('json') def handle_json(json): send(json, json=True) ``` -------------------------------- ### Emit Events from External Process Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Use this snippet in an external process (e.g., a Celery worker) to emit events to SocketIO clients when a message queue is configured. Ensure the message queue is set up in the main server. ```python socketio = SocketIO(message_queue='redis://') socketio.emit('my event', {'data': 'foo'}, namespace='/test') ``` -------------------------------- ### Flask-SocketIO Client-Side JavaScript Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/example/templates/index.html This is the main client-side JavaScript code for interacting with a Flask-SocketIO server. It handles connection, event listeners for 'connect', 'my_response', and 'my_pong', and includes interval-based ping/pong for latency testing. It also sets up event handlers for various forms to send data to the server. ```javascript $(document).ready(function() { // Connect to the Socket.IO server. // The connection URL has the following format, relative to the current page: // http[s]://:[/] var socket = io(); // Event handler for new connections. // The callback function is invoked when a connection with the // server is established. socket.on('connect', function() { socket.emit('my_event', {data: 'I\'m connected!'}); }); // Event handler for server sent data. // The callback function is invoked whenever the server emits data // to the client. The data is then displayed in the "Received" // section of the page. socket.on('my_response', function(msg, cb) { $('#log').append('
' + $('
').text('Received #' + msg.count + ': ' + msg.data).html()); if (cb) cb(); }); // Interval function that tests message latency by sending a "ping" // message. The server then responds with a "pong" message and the // round trip time is measured. var ping_pong_times = []; var start_time; window.setInterval(function() { start_time = (new Date).getTime(); $('#transport').text(socket.io.engine.transport.name); socket.emit('my_ping'); }, 1000); // Handler for the "pong" message. When the pong is received, the // time from the ping is stored, and the average of the last 30 // samples is average and displayed. socket.on('my_pong', function() { var latency = (new Date).getTime() - start_time; ping_pong_times.push(latency); ping_pong_times = ping_pong_times.slice(-30); // keep last 30 samples var sum = 0; for (var i = 0; i < ping_pong_times.length; i++) sum += ping_pong_times[i]; $('#ping-pong').text(Math.round(10 * sum / ping_pong_times.length) / 10); }); // Handlers for the different forms in the page. // These accept data from the user and send it 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; }); }); ``` -------------------------------- ### Handle Custom Events with Acknowledgement Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Define a handler for custom events that returns values to be sent back to the client as an acknowledgment. The returned values are passed to the client's callback function. ```python from flask_socketio import SocketIO socketio = SocketIO() @socketio.on('my event') def handle_my_custom_event(json): print('received json: ' + str(json)) return 'one', 2 ``` -------------------------------- ### Handle Custom Named Events with JSON Data Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Define a handler for custom named events that expect JSON data. This provides more flexibility than unnamed events. ```python from flask_socketio import SocketIO socketio = SocketIO() @socketio.on('my event') def handle_my_custom_event(json): print('received json: ' + str(json)) ``` -------------------------------- ### Custom Authentication Decorator for SocketIO Events Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/implementation_notes.md Create a custom decorator to enforce authentication for SocketIO event handlers, similar to Flask-Login's `login_required` but suitable for SocketIO. ```python import functools from flask import request from flask_login import current_user from flask_socketio import disconnect, emit def authenticated_only(f): @functools.wraps(f) def wrapped(*args, **kwargs): if not current_user.is_authenticated: disconnect() else: return f(*args, **kwargs) return wrapped @socketio.on('my event') @authenticated_only def handle_my_custom_event(data): emit('my response', {'message': '{0} has joined'.format(current_user.name)}, broadcast=True) ``` -------------------------------- ### Broadcast Message from Event Handler Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Use `broadcast=True` in `emit()` to send a message to all connected clients, including the sender. Callbacks are not invoked for broadcast messages. ```python from flask_socketio import emit @socketio.on('my event') def handle_my_custom_event(data): emit('my response', data, broadcast=True) ``` -------------------------------- ### Handle Disconnection Event Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Register a handler for the 'disconnect' event to perform actions when a client disconnects. The handler receives a `reason` argument indicating the cause. ```python from flask_socketio import disconnect @socketio.on('disconnect') def test_disconnect(reason): print('Client disconnected, reason:', reason) ``` -------------------------------- ### Handle Unnamed JSON Messages Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Register a server-side handler for incoming JSON data. Ensure the client sends data as JSON. ```python from flask_socketio import SocketIO socketio = SocketIO() @socketio.on('json') def handle_json(json): print('received json: ' + str(json)) ``` -------------------------------- ### Handle Custom Events in a Specific Namespace Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Register an event handler for a custom named event within a specific namespace. This is useful for organizing different types of communication. ```python from flask_socketio import SocketIO socketio = SocketIO() @socketio.on('my event', namespace='/test') def handle_my_custom_namespace_event(json): print('received json: ' + str(json)) ``` -------------------------------- ### Handle Errors with Flask-SocketIO Decorators Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Define error handlers for specific namespaces or a default handler for all namespaces using `@socketio.on_error()` and `@socketio.on_error_default`. ```python @socketio.on_error() # Handles the default namespace def error_handler(e): pass @socketio.on_error('/chat') # handles the '/chat' namespace def error_handler_chat(e): pass @socketio.on_error_default # handles all namespaces without an explicit error handler def default_error_handler(e): pass ``` -------------------------------- ### Eventlet Monkey Patching Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Apply monkey patching for eventlet to ensure coroutine-friendly functions are used, which is necessary when using message queues with multiple workers. ```python import eventlet eventlet.monkey_patch() ``` -------------------------------- ### Gevent Monkey Patching Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Apply monkey patching for gevent to ensure coroutine-friendly functions are used, which is necessary when using message queues with multiple workers. It's recommended to do this at the top of your main script. ```python from gevent import monkey monkey.patch_all() ``` -------------------------------- ### Handle SocketIO Connections with Flask-Login Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/implementation_notes.md Access the `current_user` object within SocketIO event handlers after Flask-Login authentication. Returns `False` to disconnect unauthenticated users. ```python import functools from flask import request from flask_login import current_user from flask_socketio import disconnect, emit @socketio.on('connect') def connect_handler(): if current_user.is_authenticated: emit('my response', {'message': '{0} has joined'.format(current_user.name)}, broadcast=True) else: return False # not allowed here ``` -------------------------------- ### Nginx Configuration for WebSocket Proxy Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/deployment.md Use this Nginx configuration to proxy HTTP and WebSocket requests to your Flask-SocketIO application. Ensure Nginx version 1.4 or newer for WebSocket support. ```nginx server { listen 80; server_name _; location / { include proxy_params; proxy_pass http://127.0.0.1:5000; } location /static/ { alias /static/; expires 30d; } location /socket.io { include proxy_params; proxy_http_version 1.1; proxy_buffering off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_pass http://127.0.0.1:5000/socket.io; } } ``` -------------------------------- ### Access Request Event Data in Error Handlers Source: https://github.com/miguelgrinberg/flask-socketio/blob/main/docs/getting_started.md Inspect `request.event` within error handlers to access the message and arguments of the triggering event for debugging purposes. ```python from flask import request @socketio.on("my error event") def on_my_event(data): raise RuntimeError() @socketio.on_error_default def default_error_handler(e): print(request.event["message"]) # "my error event" print(request.event["args"]) # (data,) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.