Files
protohackersc/echo_server_test.py

55 lines
2.0 KiB
Python

import socket
import time
def test_echo_server(host='localhost', port=40000, message="Hello, Echo Server!"):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((host, port))
print(f"Connected to {host}:{port}")
# Send the message
print(f"Sending message of length: {len(message)}")
s.sendall(message.encode())
s.shutdown(socket.SHUT_WR)
# 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) # Match the server's Sleep(100)
response = b''.join(chunks).decode()
print(f"Received {len(response)} bytes")
# Check if it's a true echo
if response == message:
print("SUCCESS: Received message matches sent message!")
else:
print("FAILURE: Received message differs from sent message!")
if len(response) != len(message):
print(f"Length mismatch: sent {len(message)}, received {len(response)}")
except ConnectionRefusedError:
print("Connection failed! Make sure the server is running.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Test with a simple message
test_echo_server()
# Test with a longer message
test_echo_server(message="This is a longer message to test the echo server's ability to handle larger strings!")
# Test with special characters
test_echo_server(message="Special chars: !@#$%^&*()")
# Test with a large message
large_message = "X" * 10000 # 10KB of data
test_echo_server(message=large_message)