Python:通过socket.io每10秒发送一次数据

Python: Send data every 10 seconds via socket.io

我有一个与这个非常相似的问题:Send data every 10 seconds via socket.io

但是:我的服务端写在Python,客户端在JavaScript

目标:

什么有效:

什么不起作用:

观察:

服务器:

import eventlet
import socketio
import threading

sio = socketio.Server(cors_allowed_origins="*", async_mode='eventlet')
app = socketio.WSGIApp(sio)


def ping_in_intervals():
    threading.Timer(5.0, ping_in_intervals).start()
    print("send ping")
    sio.emit('ping')


@sio.on('ping')
def ping(*args):
    print("received ping - send pong")
    sio.emit('pong')


ping_in_intervals()
eventlet.wsgi.server(eventlet.listen(('', 8080)), app)

客户:

const socket = io.connect('localhost:8080', {secure: true, transports: ['websocket']});

socket.on('pong', () => {
    console.log('received pong');
});

socket.on('ping', () => {
    console.log('received ping');
});

socket.on('connect', () => {
    socket.emit('ping')
});

https://github.com/miguelgrinberg/python-socketio/blob/main/examples/server/wsgi/app.py#L16-L22

处找到了解决方案

每n秒推送一次服务器消息的线程不应该使用threading启动,而是使用socketiostart_background_task函数启动。

这是工作代码:

import eventlet
import socketio

sio = socketio.Server(cors_allowed_origins="*", async_mode='eventlet')
app = socketio.WSGIApp(sio)    

def ping_in_intervals():
    while True:
        sio.sleep(10)
        sio.emit('ping')        

@sio.on('ping')
def ping(*args):
    sio.emit('pong')

thread = sio.start_background_task(ping_in_intervals)
eventlet.wsgi.server(eventlet.listen(('', 8080)), app)