websocket 的简单使用
我的应用场景是多连接用户均会收到i系统消息
由于webocket_server源码的链接关闭日志打印问题 以及需求增加websoket的token验证所以这里是直接copy了源码下来进行的修改 详情见websocket.py文件
举例:
class Websocket(object):
def __init__(self):
self.port = 6078
self.host = 0.0.0.0
self.client = []
self.server = None
def initial(self)
self.server = WebsocketServer(port, url) # 实例化websocket port-端口号 host-路由
self.server.set_fn_new_client(self.register) # 添加客户端链接
self.server.set_fn_client_left(self.unregister) # 删除客户端链接
self.server.run_forever() 启动服务
def register(self, client, server):
self.clients.append(client)
def unregister(self, client, server):
try:
self.clients.remove(client)
except Exception as error:
return
def notify(self, data): # 数据发送
"""Send a client message"""
if data and self.clients:
for user in self.clients:
try:
self.server.send_message(user, data)
except Exception as error:
continue