前端与python tornado进行websocket通信

前端代码





    
    
    
    Document
    


    
这是一段文字信息

后端python代码

import json
import logging
from abc import ABC
import tornado.websocket
import tornado.escape
import uuid
from base.BaseHandler import BaseHandler


class WebSocketHandler(BaseHandler, tornado.websocket.WebSocketHandler, ABC):
    bao_cons = set()
    bao_waiters = {}
    global con_key

    def open(self):
        sole_id = str(uuid.uuid4()).upper()
        self.con_key = sole_id
        self.bao_waiters["{}".format(sole_id)] = self
        self.bao_cons.add(self)
        self.write_message({"websocket_sole_id": sole_id})
        logging.info("websocket opened!")
        print(self.bao_cons)

    def on_message(self, message):
        if message == "close":
            self.close()
            return
        try:
            parse_data = tornado.escape.json_decode(message)
            print(parse_data)
            if parse_data["user"] and parse_data["content"]:
                user = parse_data["user"]
                content = parse_data["content"]
                if not user or not content:
                    logging.info("Date is wrong!")
                    return
                else:
                    for key in self.bao_waiters.keys():
                        if key == user:
                            try:
                                self.bao_waiters[key].write_message("{}".format(content))
                            except Exception as e:
                                logging.info(e)
                            finally:
                                logging.info("process finished!")
        except:
            for con in self.bao_cons:
                con.write_message(message)

    def check_origin(self, origin: str):
        return True

    def allow_draft76(self):
        return True

    def on_close(self):
        self.bao_cons.remove(self)
        self.bao_waiters.pop(self.con_key)
        logging.info("websocket closed!")
        print(self.bao_cons)

你可能感兴趣的:(python,前端,tornado)