python thread pool websocket client 高并发websocket客户端测试代码

本文介绍了一个使用Python实现的WebSocket并发测试程序。该程序可以同时建立5000个连接,并通过多线程每5秒发送一次数据。代码示例中包含了连接建立、消息发送及接收、错误处理等关键环节。
部署运行你感兴趣的模型镜像
import websocket
import time
import threading

SERVER_URL = "ws://192.168.1.208:7600/box/reader-"
def on_message(ws, message):
    print(message)


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


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


def on_open(ws):
    def send_trhead():
        send_info = {
        "store_id": "0001",
            "msg_type":"pay_info",
        "device_id": "device_001",
        "pay_code": "ffe2sdfdf-8sdfew-sdfsdf-ijlkj",
        "goods": [
            "C004-SD343-234",
            "D004-GE343-990",
            "G004-X343-452"
        ]
        }
        while True:
            time.sleep(5)
            ws.send(json.dumps(send_info))


    t = threading.Thread(target=send_trhead)
    t.start()




def on_start(a):
    time.sleep(a%20)
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(SERVER_URL + str(a),
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()




from threadpool import ThreadPool, makeRequests
if __name__ == "__main__":
    init_logging()
    pool = ThreadPool(5000)
    test = list()
    for ir in range(5000):
        test.append(ir)
    requests = makeRequests(on_start, test)
    [pool.putRequest(req) for req in requests]

    pool.wait()

同时5000个连接,每个连接5秒发一次数据

如果需用作socket client的测试,直接修改启动连接的函数为socket连接方式

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值