#!/usr/bin/env python3 ''' server.py Jeff Ondich, March 2026 Very simple server based on Python's socket module. ''' import sys import socket def run_server(host, port): server_socket = socket.socket() server_socket.bind((host, port)) server_socket.listen(2) # Listen for up to 2 clients simultaneously while True: connection, address = server_socket.accept() print(f'{address}: connection established') handle_connection_echo_protocol(connection, address) def handle_connection_echo_protocol(connection, address): ''' Implement an echo protocol. Note that if the connection.recv method returns a non-None value, it only guarantees the receipt of 1 byte. It might return everything the client has sent so far in a single call of connection.recv, or it might not. Since the echo protocol works just fine if you echo whatever bytes you get from the client whenever you get them, we don't worry about this connection.recv behavior here. Consider: what if your protocol has to process input one full line at a time? How would you structure your server input code in that case? ''' while True: data = connection.recv(1024) if not data: break connection.send(data) connection.close() if __name__ == '__main__': try: host = sys.argv[1] port = int(sys.argv[2]) except: print(f'Usage: {sys.argv[0]} host port', file=sys.stderr) exit() run_server(host, port)