python 利用websocket实现服务器向客户端推送消息(tornado.websocket.WebSocketHandler)

废话不多说,直接上代码,详见代码注释.

class UpdateWebSocket(WebSocketHandler,_AccountBaseHandler):
    """websocket代替轮询获取更新的数据
    """
    # 保存连接用户,用于后续推送消息
    all_shop_admins = set()

    #建立连接的时候,把用户保存到字典里面,用于后续推送消息使用 
    def open(self):
        print("new client opened")
        # 初始化
        all_shop_admins.add(self)

   # 关闭连接的时候需要清空连接用户 
    def on_close(self):   
        all_shop_admins.remove(self)

    # 项目中调用方法UpdateWebSocket.send_demand_updates(message)来给用户发送消息
    @classmethod
    def send_demand_updates(cls,message):
        # 给第一个用户推送消息
        all_shop_admins[0].write_message(message)

    def on_message(self,message):
    # 接收客户端发来的消息
        logging.info("got message %r", message)

    # 检查跨域请求,允许跨域,则直接return True,否则自定义筛选条件
    def check_origin(self, origin):
        parsed_origin = urllib.parse.urlparse(origin)
        return parsed_origin.netloc.endswith(".carrefourzone.senguo.cc")

# 可能会遇到的问题:

1.跨域请求
 WebSocket connection to 'ws://carrefourzone.senguo.cc:9887/updatewebsocket' failed: Error during WebSocket handshake: Unexpected response code:403
 
 出现上面这个问题的原因是因为我检查了跨域请求,在跨域请求里面要求url必须以".carrefourzone.senguo.cc"结尾,但是实际上我的请求url需要带端口号9887,所以websocket的server并不认可,
 也就拒绝了连接,这里一定要注意理解
2.服务器如何通过websocket推送消息给客户端
 如上面的代码,我们需要在UpdateWebSocket中定义由classmethod修饰的函数方法,比如我定义的send_demand_updates,然后在服务器的其他地方调用方法UpdateWebSocket.send_demand_updates(message)来给用户发送消息.

至于前端怎么实现的.可以查看我的另外一篇文章:Nginx代理webSocket时60s自动断开, 怎么保持长连接(https://blog.csdn.net/cm786526/article/details/79939687


你可能感兴趣的:(python,websocket,ser,python学习)