python脚本实现接收websockets消息



import requests
import json
import asyncio
import websockets
import ssl
import pathlib
import time
#注意这里的url可能是包含path的,这个path可以看开发的代码(后端和前端中都有)找到
url0 = 'wss://ip:端口/path'

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_context.check_hostname = False
# 这个cert.pem文件是必须的
localhost_pem = pathlib.Path(__file__).with_name("cert.pem")
ssl_context.load_verify_locations(localhost_pem)
ssl_context.verify_mode = ssl.CERT_REQUIRED
print('ssl_context是:', ssl_context)

async def call_api():
async with websockets.connect(uri=url0,ssl=ssl_context) as websocket:
time.sleep(20)
print('11111111111111111')
#await websocket.send('')
print('22222222222222222')
while websocket.open:
print('33333333333333333')
response = await websocket.recv()
print('444444444444444')
# do something with the response...
print('这是response:',response)

asyncio.get_event_loop().run_until_complete(call_api())