python achieve the establishment of communication websocket

Codes are as follows:

#websocket协议通信
import threading
import time
import websocket

DEF when_message (WS, Message):
     Print ( ' / n-received message: ' + Message)
 # When the connection is established, an infinite loop continuously input message to the server 
# It should separate from a thread 
DEF when_open (WS):
     Print ( ' a successful connection ' )
     DEF RUN ():
         the while True:
            A = INPUT ( ' Enter: ' )
            ws.send(a)
            time.sleep(0.5)
            if a == 'close':
                ws.close()
                break
    t = threading.Thread(target=run)
    # t.setDaemon(True)
    t.start()
def when_close(ws):
    print('连接关闭')

if __name__ == '__main__':
    ws = websocket.WebSocketApp('ws://localhost:9999/', on_message=when_message, on_open=when_open, on_close=when_close)
    ws.run_forever ()

 

Guess you like

Origin www.cnblogs.com/badbadboyyx/p/12005565.html