Locust 实现TCP协议接口并发测试

这篇博客介绍了如何在Windows环境下,利用Python的Locust库进行TCP协议接口的并发测试。通过两个Python脚本,TcpSocketServer.py作为服务器端,TcpSocketLoust.py作为客户端,展示了TCP连接、发送和接收数据的过程。Locust的命令行选项也被详细解释,用于无界面模式运行测试并生成测试报告。

环境:   运行环境win 10

安装软件:1.Locust

                  2.Python2.7

实现说明:以下两上.py文件模拟实现了一个接收请求的server端一个发送请求的client端,都是本机运行

TcpSocketServer.py:(Server端代码)

# !/usr/bin/env python3
# -*- coding:utf-8 -*-

import time
from socket import socket, AF_INET, SOCK_STREAM
import threading

buffsize = 2048

def tcplink(sock, addr):
    # print 'Accept new connection from %s:%s...' % addr
    sock.send('Welcome!')
    while True:
        try:
            # data = sock.recv(buffsize)
            data = sock.recv(buffsize).decode()
            time.sleep(1)
            if data == 'exit' or not data:
                break
            sock.send('Hello, %s!' % data)
        except Exception as e:
            print(str(e))
            break
    sock.close()
    print 'Connection from %s:%s closed.' % addr

def main():
    host = ''
    port = 12345
    ADDR = (host, port)
    tctime = socket(AF_INET, SOCK_STREAM)
    tctime.bind(ADDR)
    tctime.listen(3)

    print('Wait for connection ...')
    while True:
        sock, addr = tctime.accept()
        print 'Accept new connection from %s:%s...' % addr
        t = threading.Thread(target=tcplink, args=(sock, addr))
        t.start()
if __name__ == "__main__":
    main()

TcpSocketLoust.py:(Client端代码)

import time
import socket
from locust import Locust, TaskSet, events, task

class TcpSocketClient(socket.socket):
    # locust tcp client
    # author: Max.Bai@2017
    def __init__(self, af_inet, socket_type):
        super(TcpSocketClient, self).__init__(af_inet, socket_type)

    def connect(self, addr):
        start_time = time.time()
        try:
            super(TcpSocketClient, self).connect(addr)
        except Exception as e:
            total_time = int((time.time() - start_time) * 1000)
            events.request_failure.fire(request_type="tcpsocket", name="connect", response_time=total_time, exception=e)
        else:
            total_time = int((time.time() - start_time) * 1000)
            events.request_success.fire(request_type="tcpsocket", name="connect", response_time=total_time,
                                        response_length=0)
    def send(self, msg):
        start_time = time.time()
        try:
            super(TcpSocketClient, self).send(msg)
        except Exception as e:
            total_time = int((time.time() - start_time) * 1000)
            events.request_failure.fire(request_type="tcpsocket", name="send", response_time=total_time, exception=e)
        else:
            total_time = int((time.time() - start_time) * 1000)
            events.request_success.fire(request_type="tcpsocket", name="send", response_time=total_time,
                                        response_length=0)

    def recv(self, bufsize):
        recv_data = ''
        start_time = time.time()
        try:
            recv_data = super(TcpSocketClient, self).recv(bufsize)
        except Exception as e:
            total_time = int((time.time() - start_time) * 1000)
            events.request_failure.fire(request_type="tcpsocket", name="recv", response_time=total_time, exception=e)
        else:
            total_time = int((time.time() - start_time) * 1000)
            events.request_success.fire(request_type="tcpsocket", name="recv", response_time=total_time,
                                        response_length=0)
        return recv_data

class TcpSocketLocust(Locust):
    """
    This is the abstract Locust class which should be subclassed. It provides an TCP socket client
    that can be used to make TCP socket requests that will be tracked in Locust's statistics.
    author: Max.bai@2017
    """
    def __init__(self, *args, **kwargs):
        super(TcpSocketLocust, self).__init__(*args, **kwargs)
        self.client = TcpSocketClient(socket.AF_INET, socket.SOCK_STREAM)
        ADDR = (self.host, self.port)
        self.client.connect(ADDR)


class TcpTestUser(TcpSocketLocust):
    host = "127.0.0.1"            #连接的TCP服务的IP
    port = 12345                     #连接的TCP服务的端口
    min_wait = 100
    max_wait = 1000

    class task_set(TaskSet):
        @task
        def send_data(self):
            self.client.send("test")       #发送的数据
            data = self.client.recv(2048).decode()
            print(data)


if __name__ == "__main__":
    user = TcpTestUser()
    user.run()

 

运行方法:

1.启动一个dos窗口,进入存放TcpSocketServer.py 程序的目录下,使用命令:D:\Python2.7\python.exe TcpSocketServer.py 运行Server端程序,如以下图显示为启动成功

2.再启动一个dos窗口,进入存入程序的目录下,使用命令:locust -f D:/Python2.7/Scripts/locust_tcp/TcpSocketLocust.py --csv=test --no-web -c10 -r10 -t2,如以下图显示为请求发送成功,并生成了以test开头的测试报告

命令解释:

--no-web 
无web界面模式运行测试,需要-c和-r配合使用

-c

指定并发用户数,no-web模式下可用

-r  
指定每秒启动的用户数,no-web模式下可用

-t

指定运行的时间,no-web模式下可用,0.8.1版本不再提供t参数来指定运行时间,用-n来指定运行次数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值