功能說明: 連接websocket服務(wù)發(fā)送請求數(shù)據(jù)并接收,最后關(guān)閉連接,,完成一次websocket接口調(diào)試,,適用場景:單接口調(diào)試,或接口自動化測試 代碼: from websocket import create_connectionimport websocketimport jsonimport timeimport sysdef client(host): try: ws = create_connection(host) # 創(chuàng)建連接 ws.settimeout(10) # 設(shè)置超時(shí)時(shí)間 print (ws.getstatus()) recv = ws.recv() print ('連接信息',recv) # 請求數(shù)據(jù) t = time.time() timeStamp = int(round(t * 1000)) #毫秒級時(shí)間戳 data_dict = { 'cmd':'goTest', 'timestamp':timeStamp, 'body': {} } data_json = json.dumps(data_dict,indent=4) print ('請求參數(shù):%s'%data_json) ws.send(data_json) # 接收數(shù)據(jù) try: result = ws.recv() res_dict = json.loads(result) print ('接收數(shù)據(jù):\n',json.dumps(res_dict,indent=4,ensure_ascii=False)) except Exception as e: result = e print (result) except Exception as e: print ('服務(wù)連接失?。?,e) sys.exit() ws.shutdown()if __name__ == '__main__': host = 'ws://192.168.x.x:端口' client(host) 測試執(zhí)行: 測試結(jié)果: |
|