This time we’re building up on our code to support multiple clients, allowing our server to choose at any given time a client to interact with. No doubt this was the next logical step in the series, with still a few heavy hitters out there — persistence, logging, etc. Let’s get busy on this fifth part!
Before starting to code, I always like to break apart the logical sections of whatever it is I’m trying to program so that it is easier to understand. Just like the hardware in a computer is divided for specific functions — hard drive for storage, cpu for processes, etc. — in a program we must do the same. This concept will come into play later when breaking apart our code to expand its capabilities.
Arguably the code we have thus far, is pretty sloppy. Main reasons being: only two weeks of programming Python, not familiar with functions signatures and definitions, among others. In any case, given the primary objective of learning networking in-and-out of Python, I feel much progress has been made. This time it will be no different. We’re gonna take it to the next level by managing multiple clients and also learn a lot more!
The server we have setup uses one port, which is 443 (HTTPS). Handling multiple clients, to the extent of my research, works best using more than one port — some examples I saw in StackOverflow used a different port for each client (randomized), others had two ports, one for clients and another for system communication, among others… none that I really felt good about. From the client’s perspective, opening yet another port mights raise some flags or even be blocked.
Another option I really wanted to go with was threading to speed up the process, but due to lack of knowledge in the language I took a different, simpler approach…
If you’ve been following with the series, this should be easy to understand, if not.. oh dear. Everything we did up to last episode (File Transfer) turned into a sub-module of the listener process. A loop was created to control the flow of code and the previous loop(s) were wrapped up inside of it so that we have the listener layer working behind the scenes, allowing the user to go into any given client at a time, and back to the listener, and so on…
Another interesting point was using the KeyboardInterrupt except to allow us to break the code flow and choose a client to interact with. Anyway, at this point I feel much of what I’m saying will be easier explained in the video where you can also see the code.
Click here to download the source: [ DOWNLOAD ]