python tcp压测脚本
时间: 2024-10-27 11:04:02 浏览: 16
在Python中编写TCP压力测试脚本通常涉及到socket库的使用,目的是模拟大量并发连接请求,评估服务器的性能和负载承受能力。以下是一个简单的TCP压力测试脚本示例:
```python
import socket
import threading
# 设置目标主机和端口
host = 'your-target-host'
port = 80 # 这里假设是HTTP默认端口
def send_request(client_socket):
request = "GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n".format(host)
client_socket.sendall(request.encode())
client_socket.close()
def do_request():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((host, port))
thread = threading.Thread(target=send_request, args=(client,))
thread.start()
except Exception as e:
print(f"Error: {e}")
finally:
client.close()
# 定义并发数
concurrent_requests = 100
for _ in range(concurrent_requests):
threading.Thread(target=do_request).start()
print("Finished sending requests.")
```
这个脚本创建了多个线程,每个线程负责向指定主机发起一次TCP请求。你可以通过调整`concurrent_requests`变量来控制并发量。
阅读全文