-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
99 lines (85 loc) · 2.63 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
from time import sleep
from datetime import datetime
from threading import Thread
from queue import Queue
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit
namespace='/test'
async_mode = 'eventlet'
app = Flask(__name__)
app.config['SECRET_KEY'] = 'verysecretphrase'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
running = False
qtask = None
q = Queue()
def worker_task():
global running
print("Thread started")
while running:
""" Put blocking code that might take longer to execute here """
sleep(5)
q.put(str(datetime.now()))
print("Thread stopped")
def queue_task():
count = 0
while True:
socketio.sleep(0.5)
count += 1
if not q.empty():
item = q.get()
print(item)
q.task_done()
socketio.emit('log', item, namespace=namespace)
@app.before_first_request
def init_job():
global qtask
qtask = socketio.start_background_task(queue_task)
@app.route('/')
def index():
return render_template('index.html', async_mode=socketio.async_mode)
@socketio.on('start', namespace=namespace)
def start():
global thread
global running
if not thread == None:
if thread.is_alive():
socketio.emit('message', 'Thread is active', namespace=namespace)
return
thread = Thread(target = worker_task)
thread.daemon = True
running = True
socketio.emit('message', 'Thread created', namespace=namespace)
thread.start()
@socketio.on('stop', namespace=namespace)
def stop():
global thread
global running
running = False
if not thread == None:
if thread.is_alive():
print('Told the thread to stop')
socketio.emit('message', 'Told the thread to stop', namespace=namespace)
return
socketio.emit('message', 'Thread is not running', namespace=namespace)
# This function is called when a web browser connects
@socketio.on('connect', namespace=namespace)
def connect():
global qtask
if qtask == None:
qtask = socketio.start_background_task(queue_task)
print('Client connected', request.sid)
emit('connect')
# Notification that a client has disconnected
@socketio.on('disconnect', namespace=namespace)
def disconnect():
print('Client disconnected', request.sid)
emit('disconnect')
# Ping-pong allows Javascript in the web page to calculate the
# connection latency, averaging over time
@socketio.on('measure', namespace=namespace)
def ping_pong():
emit('pong')
if __name__ == "__main__":
socketio.run(app, host='127.0.0.1', port=8000)