python脚本实现接收websockets消息

2022/4/7 12:49:10

本文主要是介绍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())


这篇关于python脚本实现接收websockets消息的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程