sockets Python TCP sockets; simple server and client examples with annotation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

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

python tserver.py

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

python tclient.py

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.

Caveats:

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.



Got any sockets Question?