Как остановить WebSocket в нужный мне момент?

друзья. Я использую websocket-client для python. Мне необходимо открыть сокет и слушать определенное время каждую секунду. Но в какой-то момент я хочу закрыть этот сокет и через какое-то время создать с другими параметрами. Но я не понимаю, как его остановить и закрыть (удалить). Подскажите пожалуйста. Делаю так:

import websocket
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    print("### connected ###")

if __name__ == "__main__":
    ws = websocket.WebSocketApp("wss://stream.site.com:9443/ws/key@value", on_message=on_message, on_error=on_error, on_close=on_close)
    ws.on_open = on_open
    ws.keep_running = False
    ws.run_forever()
    time.sleep(3)
    ws.close(ws)

Но сокет не останавливается (не удаляется) и продолжает присылать данные. Подскажите как его остановить и удалить.


Ответы (1 шт):

Автор решения: gil9red

На основе примера библиотеки код клиента вебсокета, что завершает работу через несколько секунд.

Пример:

try:
    import thread
except ImportError:
    import _thread as thread
import time

# pip install websocket-client
import websocket


def on_open(ws):
    print(f'[on_open]')

    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send(f"Hello {i}")

        time.sleep(1)
        ws.close()

        print("thread terminating...")

    thread.start_new_thread(run, ())


def on_message(ws, message):
    print(f'[on_message] {message}')


def on_error(ws, error):
    print(f'[on_error] {error}')


def on_close(ws, close_status_code, close_msg):
    print(f'[on_close] close_status_code={close_status_code} close_msg={close_msg}')


if __name__ == "__main__":
    # From http://websocket.org/echo.html
    url = 'wss://echo.websocket.org'

    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(
        url,
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws.run_forever()
→ Ссылка