def new_client(client, server):
# clients.append(client)
pass
# 接收到客户端消息时触发
def message_received(client, server, message, msg=None):
print('客户端发来的消息: ',message)
client_room[client['handler']] = message
# 客户端关闭连接时触发
def client_left(client, server):
# server.send_message_to_all(json.dumps("close"))
# clients.remove(client['handler'])
client_room.pop(client['handler'])
print("left: ",client_room)
def send_msg(server):
while True:
message = msg_queue.get()
room_id = message.get("room_id")
for key, value in client_room.items():
if value == room_id:
key.send_message(json.dumps(message))
# server.send_message_to_all(json.dumps(message))
def start_server(server):
t_send_client = threading.Thread(target=send_msg, args=(server,), daemon=True)
t_send_client.start()
server.set_fn_new_client(new_client)
server.set_fn_message_received(message_received)
server.set_fn_client_left(client_left)
server.run_forever()
server = WebsocketServer('0.0.0.0', 8888)
t_start_server = threading.Thread(target=start_server, args=(server,), daemon=True)
t_start_server.start()