I have a question very similar to this one: Send data every 10 seconds via socket.io
But: My server is written in Python, the client is in JavaScript
The goal:
ping
from server every n secondsping
message, the server broadcasts a pong
messageWhat works:
ping
is received by server, answered with pong
, which is again received by clientping_in_intervals
every 5 secondsWhat doesn't work:
ping_in_intervals
(which triggers sending a ping
), that ping
is not received by any clientping_in_intervals
loop is active, socket connections crash every minute or so. 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
thread destabilizes the server thred, causes it to loose connections (which are reestablished right away, but they do drop every minute or so) 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
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
.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.