Socket.IO¶
Using Flask-SocketIO. Requests
arrive as message events, and responses go back the same way.
from flask import Flask
from flask_socketio import SocketIO, send
from jsonrpcserver import Result, Success, dispatch, method
app = Flask(__name__)
# A bigger message is rejected. 1,000,000 bytes is also the default.
socketio = SocketIO(app, max_http_buffer_size=1_000_000)
@method
def ping() -> Result:
return Success("pong")
@socketio.on("message")
def handle_message(message: str) -> None:
# max_batch_size: see the Security page.
if response := dispatch(message, max_batch_size=100):
send(response)
if __name__ == "__main__":
# Werkzeug's server is for development. See the Flask-SocketIO docs for
# production servers.
socketio.run(app, host="localhost", port=8000, allow_unsafe_werkzeug=True)
A notification gets nothing back. Flask-SocketIO refuses a message bigger
than max_http_buffer_size. Its default is 1,000,000 bytes, and the example
sets it explicitly. max_batch_size limits how many requests one batch can
hold. See Security.
The example runs on Werkzeug's development server. Flask-SocketIO's docs cover the production servers it supports.
Try it¶
Install Flask-SocketIO (pip install flask-socketio) and run the example.
Any Socket.IO client can call it: connect to http://localhost:8000, emit a
message event with the request string, and wait for a message event with
the response. With python-socketio,
that's SimpleClient.connect, emit("message", request) and receive().