我的函数没有关闭WebSocket连接

问题描述 投票:0回答:1

我有一个连接到实时数据流的 websocket 客户端。连接工作正常,当我运行

hello
时,它会连接到流。由于 WebSocket 服务器永久运行和发送,因此在很短的时间内会产生大量数据,我想手动关闭连接。我写了这个函数
close_connection
,但是当我调用它时没有任何反应,我不知道为什么。

这就是我的代码的样子:

import websockets
from websockets.sync.client import connect

URL = "wss://test.com/test"
AUTHENTIFICATION = {'Authorization': 'Basic someToken'}
def hello():
    with connect(URL, 
                 additional_headers = AUTHENTIFICATION) as websocket:
        message = websocket.recv()
        resp = websocket.response.status_code
        if websocket.response.status_code == 101:
            print('Connection successful')
        else: 
            print('Failure')
        for message in websocket:
            print(f"Received: {message}")

def close_connection():
    with connect(URL, 
                additional_headers=AUTHENTIFICATION) as websocket:
        websocket.close()
python websocket
1个回答
0
投票

如果你看这里,一退出就可以看到

with connect(URL, additional_headers = AUTHENTIFICATION) as websocket:

您的 websocket 连接已自行关闭。您可能需要一种方法来存储该 websocket,然后按照您想要的方式处理它。您可以查看 websocket 库本身给出的一些模式并选择其中之一。

© www.soinside.com 2019 - 2024. All rights reserved.