From fde3c8e2b8795603f4a8bea202d105e8c886c31a Mon Sep 17 00:00:00 2001 From: Gilbert Brault Date: Fri, 3 Feb 2023 13:53:48 +0100 Subject: [PATCH] Clock example (Fixes #45) --- examples/clock.py | 48 +++++++++++++++++++++++++++++++++++ examples/templates/clock.html | 31 ++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 examples/clock.py create mode 100644 examples/templates/clock.html diff --git a/examples/clock.py b/examples/clock.py new file mode 100644 index 0000000..48ea4d6 --- /dev/null +++ b/examples/clock.py @@ -0,0 +1,48 @@ +from flask import Flask, render_template +from flask_sock import Sock +import json +import time, datetime +import threading + +app = Flask(__name__) +app.config['SOCK_SERVER_OPTIONS'] = {'ping_interval': 25} + +sock = Sock(app) + +client_list = [] + + +@app.route('/') +def index(): + return render_template('clock.html') + + +def send_time(): + while True: + time.sleep(1) + clients = client_list.copy() + for client in clients: + try: + client.send(json.dumps({ + 'text': datetime.datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + })) + except: + client_list.remove(client) + + +@sock.route('/clock') +def clock(ws): + client_list.append(ws) + while True: + data = ws.receive() + if data == 'stop': + break + client_list.remove(ws) + + +if __name__ == '__main__': + t = threading.Thread(target=send_time) + t.daemon = True + t.start() + app.run() diff --git a/examples/templates/clock.html b/examples/templates/clock.html new file mode 100644 index 0000000..9a2fd14 --- /dev/null +++ b/examples/templates/clock.html @@ -0,0 +1,31 @@ + + + + Flask-Sock Clock Demo + + +

Flask-Sock Demo

+

Hit Stop to end the connection.

+

Server time:

+ + + +