heroku-python / flask-sockets

[DEPRECATED] Alternative: https://github.com/miguelgrinberg/flask-sock
MIT License
1.74k stars 167 forks source link

How to give ws.receive() a timeout value and default value? #76

Open tme-wl opened 4 years ago

tme-wl commented 4 years ago

I mean

msg = ws.receive(timeout=1, default='bob')

if client no send data, after 1 second , give a default value to msg

how to do like this? please!!!!!

dylancrockett commented 4 years ago

I am not sure why you would want to do this but I do believe gevent provides a workaround for situations like this.

For example you could do the following to achieve your timeout of 1 second:

msg = None  # be aware that None is also returned when the websocket connection has closed

# give the code within the with statement 1 second to run before it is forced to stop
with Timeout(1, False):
    msg = ws.receive()

# check if we timed out without receiving a value
if msg is None:
    msg = "bob"
# continue with your code

If you could explain why you want to do this I might be able to offer some better solutions for what you want to do.

tme-wl commented 3 years ago

our web client send msg not a regular time, but our web server must send data every 1 second. so, if I receive it, I can't send data every 1 second , if I do not receive it , I can't catch the msg.

so now , I used 2 threading to solve this,one receive msg one send data every 1 second. bug it is not pythonic.