# coding=utf-8 # 安装websocket相关库 # pip install websocket # pip install websocket-client import json import websocket from threading import Thread import time def on_message(ws, message): print(json.loads(message)) def on_error(ws, error): print(error) def on_close(ws,a,b): print("### closed ###") def on_open(ws): print("### open ###s") if __name__ == "__main__": # url = "ws://localhost:9003" url = "ws://123.57.208.174:8888" # url = "ws://192.168.3.134:9003" ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
服务端
from websocket_server import WebsocketServer msg_queue = queue.Queue() def new_client(client, server): print('开始连接1111111') # 接收到客户端消息时触发 def message_received(client, server, message, msg=None): pass # 客户端关闭连接时触发 def client_left(client, server): # server.send_message_to_all(json.dumps("close")) print('断开连接22222') def start_server(server): t_start_server = threading.Thread(target=send_msg, args=(server,),daemon=True) t_start_server.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() def send_msg(server): while True: message = msg_queue.get() # if info_data: # data = info_data[0] # server.send_message_to_all(f'111:2222:333333,{msg}') # if len(info_data) > 0: # message = info_data[0] # if message: print('message', message) server.send_message_to_all(json.dumps(message)) t_start_server = threading.Thread(target=start_server, args=(server,), daemon=True) t_start_server.start()
标签:socket,通信,server,start,client,ws,message,def From: https://www.cnblogs.com/daien522556/p/17704099.html