Skip to content

Commit

Permalink
Clock example (Fixes #45)
Browse files Browse the repository at this point in the history
  • Loading branch information
gbrault authored and miguelgrinberg committed Feb 7, 2023
1 parent 568776a commit fde3c8e
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
48 changes: 48 additions & 0 deletions examples/clock.py
Original file line number Diff line number Diff line change
@@ -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()
31 changes: 31 additions & 0 deletions examples/templates/clock.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!doctype html>
<html>
<head>
<title>Flask-Sock Clock Demo</title>
</head>
<body>
<h1>Flask-Sock Demo</h1>
<p>Hit <b>Stop</b> to end the connection.</p>
<p>Server time: <span id="clock"></span> <span id="log"></span></p>
<input type="button" id="stop" value="Stop">
<script>
const log = (text, color) => {
document.getElementById('log').innerHTML += `<span style="color: ${color}">${text}</span><br>`;
};

const socket = new WebSocket('ws://' + location.host + '/clock');
socket.addEventListener('message', ev => {
msg = JSON.parse(ev.data);
document.getElementById('clock').innerHTML = msg.text;
});
socket.addEventListener('close', ev => {
log('[Stopped]');
});
document.getElementById('stop').onclick = (ev => {
ev.preventDefault();
socket.send("stop");
ev.target.disabled = true;
});
</script>
</body>
</html>

0 comments on commit fde3c8e

Please sign in to comment.