Locust

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

janice No Comments

安装软件:1.Locust
2.Python3.8

以下是TCP 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!'.encode())
    while True:
        try:
            data = sock.recv(buffsize)
            # data = sock.recv(buffsize).decode()
            time.sleep(0.5)
            # print(data)
            if data == 'exit' or not data:
                break
            send_data = 'Hello, %s!' % data.decode()
            print(send_data)
            sock.send(send_data.encode())
        except Exception as e:
            print(str(e))
            break
    sock.close()
    print ('Connection from %s:%d 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':%d..." % addr)
        t = threading.Thread(target=tcplink, args=(sock, addr))
        t.start()

if __name__ == "__main__":
    main()

以下是TCP + Locust的改写:


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

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,response_length=0)
        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,response_length=0)
        else:
            total_time = int((time.time() - start_time) * 1000)
            events.request_success.fire(request_type="tcpsocket", name="send",
                         response_time=total_time,response_length=len(msg))


    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,response_length=0)
        else:
            total_time = int((time.time() - start_time) * 1000)
            events.request_success.fire(request_type="tcpsocket", name="recv",
                         response_time=total_time,response_length=len(recv_data))
        # super(TcpSocketClient, self).close()
        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)
        # self.client.recv(2048)


class MyTask(TaskSet):
    def on_start(self):
        # self.client.send("test".encode())       #发送的数据
        data = self.client.recv(2048)
        if data != '':
            print(data.decode())
        else:
            print("没有收到数据")


    @task(1)
    def send_data(self):
        self.client.send("test".encode())       #发送的数据
        data = self.client.recv(2048)
        if data !='':
            print(data.decode())
        else:
            print("没有收到数据")

    @task(2)
    def send_data2(self):
        self.client.send("locust".encode())  # 发送的数据
        data = self.client.recv(2048)
        if data !='':
            print(data.decode())
        else:
            print("没有收到数据")

class TcpTestUser(TcpSocketLocust):
    task_set = MyTask
    host = "127.0.0.1"            #连接的TCP服务的IP
    port = 12345                     #连接的TCP服务的端口
    # min_wait = 100
    # max_wait = 1000
    wait_time = between(0.1, 1)



if __name__ == "__main__":
    #  方法1 单连接
    # user = TcpTestUser()
    # user.run()
    #  方法2 cmd
    # pass
    #  方法3 os.system
    import os
    os.system("locust -f LocustTcpClient.py --web-host=0.0.0.0 --web-port=8999")
    # os.system("locust -f LocustTcpClient.py --no-web -c 10 -t 60 -r 5")

分类目录

关于我

 Janice 詹

QQ   455899417

janice2014@foxmail.com