flask-socketio实现简单websocket通信
from app import socketio, emit, app
from flask import request
tasks = {}
class MonitorTask(object):
def __init__(self, username, sid):
self._running = True
self.username = username
self.sid = sid
def terminate(self):
self._running = False
def get_data(self):
return {"msg": f"hahaha------{self.username}"}
def run(self):
while self._running:
data = self.get_data()
app.logger.info(data)
socketio.emit("response", {"msg": data}, namespace='/transaction_cycle_life', room=self.sid)
socketio.sleep(3)
@socketio.on("join", namespace="/transaction_cycle_life")
def join(data):
username = data.get('username')
emit("response", {"msg": username})
task = MonitorTask(username, request.sid)
thread = socketio.start_background_task(task.run)
tasks[request.sid] = {'task': task, 'thread': thread}
app.logger.info(tasks)
@socketio.on("leave", namespace="/transaction_cycle_life")
def leave(*args):
tasks[request.sid]['task'].terminate()
app.logger("trigger leave ----------")
del tasks[request.sid]
emit("disconnect")
@socketio.on("message", namespace="/transaction_cycle_life")
def message(data):
app.logger.info(data)
@socketio.on("connect", namespace="/transaction_cycle_life")
def connect():
app.logger.info('connect------')
@socketio.on("disconnect", namespace="/transaction_cycle_life")
def disconnect():
try:
tasks[request.sid]['task'].terminate()
del tasks[request.sid]
app.logger.info("disconnect -------------------")
except KeyError as ke:
app.logger.info("key error pass")