84 lines
2.4 KiB
Python
84 lines
2.4 KiB
Python
import socket
|
|
import time
|
|
|
|
def print_bytes(prefix, data):
|
|
"""Print raw bytes with both hex and ASCII representation"""
|
|
hex_data = ' '.join(f'{b:02x}' for b in data)
|
|
ascii_data = ''.join(chr(b) if 32 <= b <= 126 else '.' for b in data)
|
|
print(f"{prefix} (hex): {hex_data}")
|
|
print(f"{prefix} (ascii): {ascii_data}")
|
|
|
|
def create_client(name):
|
|
"""Create and connect a client, handle initial connection sequence"""
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
sock.connect(('localhost', 40000))
|
|
|
|
# Receive welcome message
|
|
welcome = sock.recv(1024)
|
|
print(f"\n=== {name} receiving welcome message ===")
|
|
print_bytes("Received", welcome)
|
|
|
|
# Send username
|
|
username = f"{name}\n".encode('ascii')
|
|
print(f"\n=== {name} sending username ===")
|
|
print_bytes("Sending", username)
|
|
sock.send(username)
|
|
|
|
# Receive room info
|
|
room_info = sock.recv(1024)
|
|
print(f"\n=== {name} receiving room info ===")
|
|
print_bytes("Received", room_info)
|
|
|
|
return sock
|
|
|
|
def main():
|
|
# Create first client
|
|
print("\nConnecting client 1...")
|
|
client1 = create_client("Alice")
|
|
|
|
time.sleep(1) # Small delay between connections
|
|
|
|
# Create second client
|
|
print("\nConnecting client 2...")
|
|
client2 = create_client("Bob")
|
|
|
|
# Client 1 should receive notification about client 2
|
|
join_notification = client1.recv(1024)
|
|
print("\n=== Alice receiving Bob's join notification ===")
|
|
print_bytes("Received", join_notification)
|
|
|
|
# Client 1 sends a message
|
|
message1 = "Hello Bob!\n".encode('ascii')
|
|
print("\n=== Alice sending message ===")
|
|
print_bytes("Sending", message1)
|
|
client1.send(message1)
|
|
|
|
# Client 2 receives the message
|
|
received1 = client2.recv(1024)
|
|
print("\n=== Bob receiving message ===")
|
|
print_bytes("Received", received1)
|
|
|
|
# Client 2 sends a reply
|
|
message2 = "Hi Alice!\n".encode('ascii')
|
|
print("\n=== Bob sending message ===")
|
|
print_bytes("Sending", message2)
|
|
client2.send(message2)
|
|
|
|
# Client 1 receives the reply
|
|
received2 = client1.recv(1024)
|
|
print("\n=== Alice receiving message ===")
|
|
print_bytes("Received", received2)
|
|
|
|
# Close connections
|
|
print("\nClosing connections...")
|
|
client1.close()
|
|
|
|
received1 = client2.recv(1024)
|
|
print("\n=== Bob receiving message ===")
|
|
print_bytes("Received", received1)
|
|
|
|
client2.close()
|
|
|
|
if __name__ == "__main__":
|
|
main()
|