使用 locust 对 tcp 做长连接的压测,代码如下
import time
import random
# from socket import socket, AF_INET, SOCK_STREAM
import socket
from locust import Locust, TaskSet, events, task
class TcpSocketClient(socket.socket):
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.
"""
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 = "10.20.28.133"
port = 8173
class task_set(TaskSet):
@task
def send_data(self):
self.client.send(b"\xff\xff\x00\n\xc9\x00\x01\x00\xa6\r")
time.sleep(5)
if __name__ == "__main__":
user = TcpTestUser()
user.run()
建立一个链接时正常,建立 2 个连接时报错如下:
请大神答疑解惑