添加取消SSL验证

This commit is contained in:
John Smith 2018-06-02 22:09:55 +08:00
parent 102674fcad
commit 11bacf8d43
2 changed files with 14 additions and 4 deletions

View File

@ -5,6 +5,8 @@ import struct
from asyncio import gather, sleep, CancelledError
from collections import namedtuple
from enum import IntEnum
# noinspection PyProtectedMember
from ssl import _create_unverified_context
import requests
import websockets
@ -26,13 +28,15 @@ class BLiveClient:
HEADER_STRUCT = struct.Struct('>I2H2I')
HeaderTuple = namedtuple('HeaderTuple', ('total_len', 'header_len', 'proto_ver', 'operation', 'sequence'))
def __init__(self, room_id, loop=None):
def __init__(self, room_id, ssl=True, loop=None):
"""
:param room_id: URL中的房间ID
:param ssl: True表示用默认的SSLContext验证False表示不验证也可以传入SSLContext
:param loop: 协程事件循环
"""
self._short_id = room_id
self._room_id = None
self._ssl = ssl if ssl else _create_unverified_context()
self._websocket = None
# 未登录
self._uid = 0
@ -96,7 +100,7 @@ class BLiveClient:
while True:
try:
# 连接
async with websockets.connect(self.WEBSOCKET_URL) as websocket:
async with websockets.connect(self.WEBSOCKET_URL, ssl=self._ssl, loop=self._loop) as websocket:
self._websocket = websocket
await self._send_auth()

View File

@ -17,9 +17,15 @@ class MyBLiveClient(BLiveClient):
def main():
loop = get_event_loop()
client = MyBLiveClient(6, loop)
# 如果SSL验证失败或连接卡死就把第二个参数设为False
client = MyBLiveClient(139, True, loop)
client.start()
loop.call_later(5, client.stop, loop.stop)
# 5秒后停止测试用
# loop.call_later(5, client.stop, loop.stop)
# 按Ctrl+C停止
# import signal
# signal.signal(signal.SIGINT, lambda signum, frame: client.stop(loop.stop))
try:
loop.run_forever()