websocket_client

大兔子大兔子 提交于 2019-11-28 20:50:56

代码如下:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
运行环境:win7_x86 python3.7.3_x86
运行命令:
"""

import asyncio
import pathlib
import ssl
import websockets
import websocket
import os

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
# ssl_context = ssl._create_unverified_context()
# ssl_context = ssl._create_unverified_context()
localhost_pem = pathlib.Path(__file__).with_name("localhost.pem")
# ssl_context.load_verify_locations(localhost_pem)
# 加载信任根证书
# ssl_context.verify_mode = ssl.CERT_NONE

cert_path = r'V:\my_work\ief\DESKTOP-P59IMSG'
cert_dict = ['oy1dzprlva_ca.crt', 'oy1dzprlva_private_cert.crt', 'oy1dzprlva_private_cert.key']
# cert_path = r'V:\my_work\ief\DESKTOP-P59IMSG\system'
# cert_dict = ['sys_ca.crt', 'sys_private_cert.crt', 'sys_private_cert.key']

ssl_context.load_verify_locations(os.path.join(cert_path, cert_dict[0]))
ssl_context.load_cert_chain(certfile=os.path.join(cert_path, cert_dict[1]),
                            keyfile=os.path.join(cert_path, cert_dict[2]))

def hello():
    uri = "wss://localhost:8765"
    uri = "wss://ief2-edgeaccess.cn-north-1.myhuaweicloud.com:443/"
    try:
        websocket = websockets.connect(uri, ssl=ssl_context)
        print(dir(websocket))
    except Exception as ex:
        print("ERROR", ex)

def hello2():
    websocket.enableTrace(True)
    try:
        ws = websocket.create_connection("wss://ief2-edgeaccess.cn-north-1.myhuaweicloud.com:443",
                                         sslopt={'ca_certs': os.path.join(cert_path, cert_dict[0]),
                                                 'check_hostname': False,
                                                 'ca_cert_path': cert_path,
                                                 'keyfile': os.path.join(cert_path, cert_dict[2]),
                                                 'certfile': os.path.join(cert_path, cert_dict[1]),
                                                 }
                                         )
        print("Sending 'Hello, World'...")
        ws.send("Hello, World")
        print("Sent")
        print("Receiving...")
        result = ws.recv()
        print("Received '%s'" % result)
        ws.close()
    except Exception as ex:
        print(ex)
        print("ERROR", ex)
hello2()

 

代码如上:

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!