miguelgrinberg / simple-websocket

Simple WebSocket server and client for Python.
MIT License
79 stars 17 forks source link

Ping pong support #8

Closed pfw closed 2 years ago

pfw commented 2 years ago

This is my cut at adding ping/pong support. It is straightforward if put directly on the receive() method and has the advantage of being able to set different values for different endpoints within the one app. I can also see the value in just having ping/pong always enabled, it is in the spec and clients must support it but I guess having as an option would allow for dealing with broken clients if they appear. I'm going to have a look at the tests but I got myself confused on with those to start with, need to understand what is going on with mock sockets.


@sock.route("/echo")
def echo(ws):
    while True:
        data = ws.receive(ping_interval=5)
        ws.send(data)
miguelgrinberg commented 2 years ago

Unfortunately this isn't a general solution that can be used by this package.

Also as a side note, I believe you haven't tested your solution well. Consider, for example an application that calls receive(timeout=1, ping_interval=25) in a loop. This would never send any pings, as far as I can see.

pfw commented 2 years ago

Oh definitely the mix of timeout and ping interval means one or the other if both are specified, that is understood with this, it's certainly not a fundamental issue with sending pings in a receive loop as it would just require maintaining a timer rather than the flag.

For an app that never has a receive loop you'd need to have another loop waiting on a timeout to send the ping. This is the biggest complication being on a thread rather than an event loop.