我经常用wscat 来测试后台服务提供的websocket接口。wscat 作为一个测试工具很好使用,唯一的不足是,不是所有的环境都允许安装nodejs。索性自己用python写一个。

import sys
import ssl
import json
import asyncio
from websockets import connect
from aioconsole import get_standard_streams
import websockets

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

async def readCMD(websocket, reader):
    while True:
        input_line = await reader.readline()
        if len(input_line) == 0 or input_line.lower() == "exit":
            websocket.close()
            return
        try:
            input_json = json.loads(input_line)
            await websocket.send(json.dumps(input_json))
        except:
            print(sys.exc_info())
async def readWS(websocket, writer):
    while True:
        try:
            response = await websocket.recv()
            writer.write(response+'\n')
        except (websockets.exceptions.ConnectionClosed, RuntimeError):
            return
        except:
            print(sys.exc_info())

async def wscat(uri):
    reader, writer = await get_standard_streams()
    async with connect(uri, ssl=ssl_context) as websocket:

        await asyncio.gather(readCMD(websocket, reader), readWS(websocket, writer))
asyncio.run(wscat("wss://127.0.0.1/connection.data"))

1 对 “Python 版的wscat”的想法;

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据