85 lines
3.0 KiB
Python
85 lines
3.0 KiB
Python
import socket
|
|
import threading
|
|
import time
|
|
import random
|
|
import string
|
|
|
|
def random_string(length):
|
|
"""Generate a random string of fixed length"""
|
|
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
|
|
|
def echo_client(client_id, message):
|
|
"""Individual client function that connects and sends/receives data"""
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
try:
|
|
s.connect(('localhost', 40000))
|
|
print(f"Client {client_id}: Connected")
|
|
|
|
# Send the message
|
|
print(f"Client {client_id}: Sending message of length {len(message)}")
|
|
s.sendall(message.encode())
|
|
|
|
# Receive the response in chunks
|
|
chunks = []
|
|
bytes_received = 0
|
|
while bytes_received < len(message):
|
|
chunk = s.recv(1024)
|
|
if not chunk:
|
|
break
|
|
chunks.append(chunk)
|
|
bytes_received += len(chunk)
|
|
time.sleep(0.1)
|
|
|
|
response = b''.join(chunks).decode()
|
|
|
|
# Verify response
|
|
if response == message:
|
|
print(f"Client {client_id}: SUCCESS - Message verified ({len(response)} bytes)")
|
|
else:
|
|
print(f"Client {client_id}: FAILURE - Message mismatch!")
|
|
print(f"Client {client_id}: Expected length: {len(message)}, Got: {len(response)}")
|
|
|
|
except Exception as e:
|
|
print(f"Client {client_id}: Error - {str(e)}")
|
|
|
|
def run_parallel_test(num_clients=5, message_size_range=(100, 5000)):
|
|
"""Run multiple clients in parallel"""
|
|
threads = []
|
|
|
|
print(f"Starting parallel test with {num_clients} clients...")
|
|
|
|
# Create and start threads
|
|
for i in range(num_clients):
|
|
# Generate random message size between min and max range
|
|
msg_size = random.randint(*message_size_range)
|
|
message = random_string(msg_size)
|
|
|
|
thread = threading.Thread(target=echo_client, args=(i, message))
|
|
threads.append(thread)
|
|
thread.start()
|
|
# Small delay between starting threads
|
|
time.sleep(0.1)
|
|
|
|
# Wait for all threads to complete
|
|
for thread in threads:
|
|
thread.join()
|
|
|
|
print("All clients finished")
|
|
|
|
if __name__ == "__main__":
|
|
# Test 1: Few clients with small messages
|
|
print("\nTest 1: 3 parallel clients with small messages")
|
|
run_parallel_test(num_clients=3, message_size_range=(100, 500))
|
|
|
|
time.sleep(1) # Wait between tests
|
|
|
|
# Test 2: More clients with varying message sizes
|
|
print("\nTest 2: 5 parallel clients with varying message sizes")
|
|
run_parallel_test(num_clients=5, message_size_range=(1000, 5000))
|
|
|
|
time.sleep(1) # Wait between tests
|
|
|
|
# Test 3: Stress test with many clients
|
|
print("\nTest 3: Stress test with 10 parallel clients")
|
|
run_parallel_test(num_clients=10, message_size_range=(500, 10000))
|