import asyncio

import websockets

import logging

from datetime import datetime

# 接続先(モック確認時はlocalhost:8000、現場は適宜変更)

WS_URL = “ws://localhost:8000”

# ログファイル名

LOG_FILE = “ws_receive_log.txt”

logging.basicConfig(level=logging.INFO, format=’%(asctime)s %(message)s’)

async def listen():

    logging.info(f”接続開始: {WS_URL}”)

    with open(LOG_FILE, “a”, encoding=”utf-8″) as f:

        f.write(f”\n=== 起動: {datetime.now()} ===\n”)

    async with websockets.connect(WS_URL) as ws:

        logging.info(“接続成功”)

        async for message in ws:

            timestamp = datetime.now().strftime(“%Y-%m-%d %H:%M:%S.%f”)

            log_line = f”{timestamp} | {message}\n”

            print(log_line, end=””)

            with open(LOG_FILE, “a”, encoding=”utf-8″) as f:

                f.write(log_line)

asyncio.run(listen())

タイトルとURLをコピーしました