[英]Python: Send data every 10 seconds via socket.io
I have a question very similar to this one: Send data every 10 seconds via socket.io我有一个与此非常相似的问题: 每 10 秒通过 socket.io 发送数据
But: My server is written in Python, the client is in JavaScript但是:我的服务端写在Python,客户端写在JavaScript
The goal:目标:
ping
from server every n secondsping
ping
message, the server broadcasts a pong
messageping
消息时,服务器广播pong
消息What works:什么有效:
ping
is received by server, answered with pong
, which is again received by clientping
由服务器接收,用pong
应答,客户端再次接收ping_in_intervals
every 5 secondsping_in_intervals
What doesn't work:什么不起作用:
ping_in_intervals
(which triggers sending a ping
), that ping
is not received by any clientping_in_intervals
(触发发送ping
)时,任何客户端都不会收到该ping
ping_in_intervals
loop is active, socket connections crash every minute or so.ping_in_intervals
循环处于活动状态时,套接字连接每分钟左右崩溃一次。 If the method is commented out, then socket connection stays stable. Observations:观察:
ping_in_intervals
is running in doesn't seem to properly work together with the wsgi server thread.ping_in_intervals
的线程似乎无法与 wsgi 服务器线程一起正常工作。ping_in_intervals
thread destabilizes the server thred, causes it to loose connections (which are reestablished right away, but they do drop every minute or so) ping_in_intervals
线程使服务器 thred 不稳定,导致它失去连接(立即重新建立连接,但它们确实每分钟左右断开一次)Server:服务器:
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)
Client:客户:
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')
});
Found the solution at https://github.com/miguelgrinberg/python-socketio/blob/main/examples/server/wsgi/app.py#L16-L22在https://github.com/miguelgrinberg/python-socketio/blob/main/examples/server/wsgi/app.py#L16-L22找到解决方案
The thread, which pushes server messages every n seconds, shouldn't be started using threading
, but instead using the start_background_task
function of socketio
.该线程每 n 秒推送一次服务器消息,不应使用
threading
启动,而应使用start_background_task
的 start_background_task socketio
。
Here's the working code:这是工作代码:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.