socketsPython TCP sockets; simple server and client examples with annotation


These are two sample programs that work together. One is a simple server, the other a simple client. Start the server in one window:


Edit the server address in the client source file if desired. Then run


The client connects to the server, then asks for input from the console, then sends it to the server. For each received buffer, the server prepends some canned info and sends it back to the client.

I've worked around certain pitfalls that arise in porting code between python2 and python3 -- in particular the bytes vs strings differences. A full explanation of that would require a lot of space and distract from the socket focus.


The server example, in particular, is focused on the socket operations a server will perform, but serialized for clarity. Hence, it only accepts a single connection at a time. A "real" program would either fork a new process to handle each connection, or use select to handle multiple connections at once.

Real programs would handle exceptions in the various socket calls, and recover or exit gracefully.

Real programs would need to worry about message boundaries (since TCP doesn't respect those). Since these programs send single buffers at a time triggered by user input, that has been ignored.