Python測試Websocket接口

前言

Websocket的詳解再也不介紹,個人上一篇文章已經介紹過了。html

安裝

pip install websocket


運行會報錯,還須要依賴包websocket-clientweb

pip install websocket-client

示例

使用一個demo測試網站:https://www.websocket.org/echo.html 進行演示。json

import json
from websocket import create_connection

url = 'wss://echo.websocket.org'#websocket鏈接地址,地址爲虛擬地址
#websocket.enableTrace(True)                      #打開跟蹤,查看日誌
while True:
    ws = create_connection(url)           #建立鏈接
    data =input('輸入傳輸消息:')       #測試數據
    # new_data=json.dumps(data,ensure_ascii=False)     #將data轉化爲字符串
    ws.send(data)                                #發送請求
    print('收到回覆消息:',ws.recv())                                 #打印服務器響應數據
    if data == 'q':
        ws.close()                                        #關閉鏈接
        break

相關文章
相關標籤/搜索