Simple TCP Client-Server Communication in Python
Objective
To understand basic socket programming and client-server communication by creating a simple TCP client and server. The client will connect to the server, send a message, and the server will respond.
Server Code
The server script will listen for incoming connections, receive messages from the client, and send a response back.
pythonCopy code# server.pyimport socket
def start_server(): # Define server host and port host = '127.0.0.1' # Localhost port = 65432 # Port to listen on (non-privileged ports are > 1023)
# Create a socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the address and port server_socket.bind((host, port)) # Enable the server to accept connections (max 1 queued connection) server_socket.listen(1) print(f"Server listening on {host}:{port}") while True: # Wait for a connection client_socket, client_address = server_socket.accept() print(f"Connection from {client_address} has been established.") # Receive data from the client data = client_socket.recv(1024).decode('utf-8') print(f"Received from client: {data}") # Send a response back to the client response = "Hello, Client! Message received." client_socket.send(response.encode('utf-8')) # Close the connection client_socket.close() print(f"Connection with {client_address} closed.")
if __name__ == "__main__": start_server()
Client Code
The client script will connect to the server, send a message, and receive a response.
pythonCopy code# client.pyimport socket
def start_client(): # Define server host and port host = '127.0.0.1' # Server address port = 65432 # Server port # Create a socket object client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Connect to the server client_socket.connect((host, port)) print(f"Connected to server {host}:{port}") # Send a message to the server message = "Hello, Server!" client_socket.send(message.encode('utf-8')) # Receive a response from the server response = client_socket.recv(1024).decode('utf-8') print(f"Received from server: {response}") except ConnectionError as e: print(f"Connection error: {e}") finally: # Close the connection client_socket.close()
if __name__ == "__main__": start_client()
How to Run the Code
Navigate to the directory where server.py is located. Open another terminal window. Navigate to the directory where client.py is located. Explanation
The server is set up to listen on localhost (127.0.0.1) and port 65432. It creates a socket, binds it to the specified address, and starts listening for incoming connections. When a client connects, it accepts the connection, receives data, and sends a response back. It then closes the connection with the client. The client connects to the server at localhost on port 65432. It sends a message to the server and waits for a response. Once it receives the response, it prints the message and closes the connection. This exercise introduces the basics of socket programming, demonstrating how to create a TCP client and server that communicate over a network.