核心代码:
@accept_websocket def get_log(req): if req.is_websocket(): print('收到websocket请求') with open(settings.LOG_FILE, 'r', encoding='UTF-8') as f: log_length = len(f.readlines()) time.sleep(1) while True: with open(settings.LOG_FILE, 'r', encoding='UTF-8') as f: contents = f.readlines() length_tmp = len(contents) for i in range(log_length, length_tmp): req.websocket.send(contents[i].encode('utf-8')) log_length = length_tmp time.sleep(1)
效果:
参考:
https://www.cnblogs.com/sui776265233/p/10176275.html#_labelTop
--------2019/07/25 补充vue采坑--------
vue端不能像原生js那么写:
原生js写法:
2020/08/19 补充:发送应该在确认连接完成后,否则会报错