1.下载必须的包 https://github.com/Pithikos/python-websocket-server,解压缩并把文件夹名‘python-websocket-server-master’ 改为‘websocket’
2.websocket文件夹内只保留websocket_server文件夹和server.py
3.稍微修改server.py的源码
1 from websocket_server import WebsocketServer 2 3 # Called for every client connecting (after handshake) 4 def new_client(client, server): 5 print("New client connected and was given id %d" % client['id']) 6 #server.send_message_to_all("a new client...") 7 server.send_message(client,"请问有什么可以帮到您?") 8 9 10 # Called for every client disconnecting 11 def client_left(client, server): 12 print("Client(%d) disconnected" % client['id']) 13 14 15 # Called when a client sends a message 16 def message_received(client, server, message): 17 if len(message) > 200: 18 message = message[:200]+'..' 19 print("Client(%d)_address%s said: %s" % (client['id'],client['address'], message)) 20 server.send_message(client,'用户编号'+str(client['id'])+':'+message) 21 22 23 PORT=9001 24 server = WebsocketServer(PORT,host="192.168.150.128") 25 server.set_fn_new_client(new_client) 26 server.set_fn_client_left(client_left) 27 server.set_fn_message_received(message_received) 28 server.run_forever()