try: while True: data = await reader.read(1024) if not data: break message = data.decode().strip() if message == "ping": writer.write(b"pong\n") await writer.drain() except Exception as e: print(f"Error with {addr}: {e}") finally: writer.close() print(f"Connection closed: {addr}")
while True: writer.write(b"ping\n") await writer.drain()
response = await reader.read(1024) if not response or response.decode().strip() != "pong": print(f"Connection {conn_id} bad response: {response}") break
tasks = [] for i in range(new_connections): task = asyncio.ensure_future(client_connection(current_count + i)) tasks.append(task) connections.append(task)
if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python long_client.py <total_connections>") sys.exit(1)
try: total = int(sys.argv[1]) if total <= 0: raise ValueError except ValueError: print("Invalid connection count. Must be positive integer.") sys.exit(1)
start_time = time.time() print(f"Starting long connection test with {total} connections") main(total) print(f"Test completed in {time.time()-start_time:.2f} seconds")
短请求版本
client_shot.py
1 2 3 4 5 6 7 8 9 10 11 12
import socket
def send_ping(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect(('192.168.1.19', 4444)) s.sendall(b"ping\n") response = s.recv(1024) print(f"Received: {response.decode().strip()}")