import socket # Configuration TCP_IP = '127.0.0.1' # The server's IP address (localhost in this case) TCP_PORT = 49152 # The port the server is listening on BUFFER_SIZE = 1024 # The maximum amount of data to be received at once MESSAGE = b"rppairing" # Data must be in bytes try: # 1. Create a TCP/IP socket # socket.AF_INET specifies the IPv4 address family # socket.SOCK_STREAM specifies the TCP protocol (stream socket) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # 2. Connect the socket to the remote address and port s.connect((TCP_IP, TCP_PORT)) print(f"Connecting to {TCP_IP} port {TCP_PORT}") # 3. Send data s.sendall(MESSAGE) # Use sendall() for reliable transmission of all data print(f"Sending: {MESSAGE!r}") # 4. Receive data data = s.recv(BUFFER_SIZE) print(f"Received data: {data!r}") # The socket is automatically closed when exiting the 'with' block except ConnectionRefusedError: print(f"Connection failed. Ensure a server is running on {TCP_IP}:{TCP_PORT}") except Exception as e: print(f"An error occurred: {e}")