canporter/client_emulator.py

94 lines
3.0 KiB
Python
Raw Permalink Normal View History

2024-12-11 19:38:55 +00:00
import socket
import threading
import time
import random
class TCPClient:
def __init__(self, host='127.0.0.1', port=3169):
self.host = host
self.port = port
self.client_socket = None
self.is_running = False # Control flag for background tasks
def connect(self):
"""Connect to the server."""
try:
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client_socket.connect((self.host, self.port))
self.is_running = True
print(f"Connected to server at {self.host}:{self.port}")
except Exception as e:
print(f"Error connecting to server: {e}")
def listen(self):
"""Listen for messages from the server."""
try:
while self.is_running:
data = self.client_socket.recv(1024)
if not data:
break
print(f"Received: {data.decode()}")
except Exception as e:
print(f"Error receiving data: {e}")
finally:
self.is_running = False
print("Disconnected from server.")
def send_ping(self):
"""Background task to send 'ping' messages."""
try:
while self.is_running:
if self.client_socket:
self.client_socket.sendall("ping".encode())
print(f"Sent: ping")
time.sleep(10) # Send 'ping' every 10 seconds
except Exception as e:
print(f"Error sending ping: {e}")
def disconnect(self):
"""Disconnect from the server."""
self.is_running = False
if self.client_socket:
try:
self.client_socket.close()
except Exception:
pass
print("Disconnected from server.")
def client_behaviour(client_id, host, port):
"""Simulate a client's behaviour."""
client = TCPClient(host, port)
while True:
client.connect()
# Start listening and ping threads
listen_thread = threading.Thread(target=client.listen, daemon=True)
listen_thread.start()
ping_thread = threading.Thread(target=client.send_ping, daemon=True)
ping_thread.start()
# Stay connected for a random duration
time.sleep(random.randint(60, 180))
client.disconnect()
# Wait for a random interval before reconnecting
time.sleep(random.randint(5, 60))
def generate_clients(host='127.0.0.1', port=3169, num_clients=5):
"""Generate multiple clients using threads."""
threads = []
for i in range(num_clients):
client_thread = threading.Thread(target=client_behaviour, args=(i, host, port), daemon=True)
threads.append(client_thread)
client_thread.start()
print(f"Client {i} started.")
# Keep the main thread alive
for thread in threads:
thread.join()
if __name__ == "__main__":
generate_clients(num_clients=10)