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
| import random import threading
import time
import datetime from flask import Flask, render_template from flask_sockets import Sockets from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler
app = Flask(__name__) sockets = Sockets(app)
def run_async(f): def wrapper(*args, **kwargs): thr = threading.Thread(target = f, args = args, kwargs = kwargs) thr.start() thr.setName("func-{}".format(f.__name__)) print("线程id={},\n线程名称={},\n正在执行的线程列表:{},\n正在执行的线程数量={},\n当前激活线程={}".format( thr.ident,thr.getName(),threading.enumerate(),threading.active_count(),thr.isAlive) ) return wrapper
@app.route('/test') def test(): return render_template('test2.html')
WS = {}
@sockets.route('/echo') def echo_socket(ws): global WS print('/echo:', ws) while not ws.closed: try: WS['echo'] = ws print('WS', WS) str_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') message = ws.receive() ws.send("time:%s,msg: %s"%(str_time,str(message)))
except Exception as e: print('error:',e)
@sockets.route('/poll') def test2_socket(ws): try: print('/poll:', ws) n = ws.receive() print('n-----', n) print('WS-----', WS)
WS['echo'].send("receive for poll: " + n)
except Exception as e: print('error:',e)
@sockets.route('/test3') def test3_socket(ws): try: print('/test3:', ws) while True: time.sleep(3) t = random.randint(1,100) ws.send("while True number: " + str(t)) except Exception as e: print('error:',e)
if __name__ == "__main__": try: server = pywsgi.WSGIServer(('0.0.0.0', 7070), application=app, handler_class=WebSocketHandler) print("web server start ... ") server.serve_forever() except Exception as e: print('error:',e)
|