Socket programming enables two nodes on a network to communicate by establishing a connection. One socket acts as a listener, bound to a specific IP and port, while the other socket initiates the connection. Typically, the server sets up the listening socket, and the client connects to it.
server2.py: TCP Server for String Reversal
This script sets up a TCP server that listens on localhost (127.0.0.1) and port 65433. Its functionality includes receiving strings from a client, reversing them, and responding back. If the client sends the command "shutdown", the server terminates gracefully.
Highlights:
Uses socket.AF_INET (IPv4) and socket.SOCK_STREAM (TCP) for communication.
Reverses strings received from the client and prints them to the console.
Recognizes the "shutdown" command to exit the loop and close connections.
Execution Behavior:
The client sends a string, and the server replies with its reversed version.
When the "shutdown" command is received, the server stops running.
server1.py: Simplified TCP Server
This script demonstrates another TCP server that listens on port 65432. It is designed with clearer code organization by defining constants HOST and PORT. The server accepts connections in a loop and displays the data received from the client.
Highlights:
Dynamically prints the host and port of the connection.
Incorporates a basic try-except block for error handling.
Execution Behavior:
The client sends messages like "hello", which the server prints to the console.
Both programs demonstrate foundational TCP server functionalities, showcasing different styles of implementation and varying degrees of robustness in socket programming.