Python Socket.IO

5.16.1 · active · verified Mon Apr 06

python-socketio is a comprehensive Python implementation of the Socket.IO real-time communication protocol, offering both server and client functionalities. It enables low-latency, bidirectional, and event-based communication between clients (often web browsers) and a Python server. The library is actively maintained with frequent releases, providing compatibility with various asynchronous frameworks and web servers.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Socket.IO server using `eventlet` and a simple HTML client. The server defines handlers for `connect`, `my_message`, and `disconnect` events. The client connects, sends a message, and receives a response. An `index.html` file is created on the fly for easy testing. Remember to `pip install eventlet` for this example to run.

import socketio
import eventlet

sio = socketio.Server(cors_allowed_origins="*")
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.emit('my response', {'data': data}, room=sid)

@sio.event
def disconnect(sid):
    print('disconnect ', sid)

if __name__ == '__main__':
    # index.html for testing
    with open('index.html', 'w') as f:
        f.write('''
            <!DOCTYPE html>
            <html>
            <head>
                <title>Socket.IO Test</title>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
            </head>
            <body>
                <h1>Socket.IO Test</h1>
                <script type="text/javascript">
                    var socket = io();
                    socket.on('connect', function() {
                        console.log('Connected!');
                        socket.emit('my_message', 'Hello from browser!');
                    });
                    socket.on('my response', function(data) {
                        console.log('Received:', data);
                    });
                    socket.on('disconnect', function() {
                        console.log('Disconnected!');
                    });
                </script>
            </body>
            </html>
        ''')
    print("Starting server on http://localhost:5000")
    eventlet.wsgi.server(eventlet.listen(('', 5000)), app)

view raw JSON →