Today, I'm spending the day learning in public about socket programming (in Python π).
My starting point is this:
βI think sockets are like tunnels/roads that allow different programs to talk to each other directly.β
This π§΅ will evolve as I learn and experiment π
My idea is to experiment a bit with sockets in the REPL, then probably build a toy program that uses sockets to send random information through sockets.
We create the socket as usual, but then connect to the host name the computer printed, instead of "localhost".
And then, send something!
That's it!
Now, I just have to receive the message on the computer!
Here's a picture proving it happened π
Take a look at the bottom of the two interpreters!
One sent the msg, the other received it π
I feel like a child π π
At this point, I've seen enough to start understanding what server sockets really do.
(I think)
The client socket seems to be responsible for sending and receiving data, while the server socket seems to be responsible for accepting connections
_and_ creating _client_ sockets.
There's an interesting nuance to sockets...
How can I know that I received the whole message?
The HOWTO I'm reading gives 4 options:
π fixed length msgs
π delimited msgs
π msgs indicate their length in the beginning
π sockets are single-use only
Here's a basic overview π
Of course, all these methods have some gotchas and the dummy code I shared above isn't as robust as it should be!
It's just a basic rendition of each method.
(For the snippets above, the set up of the client and server sides was this π)
I have been tweeting about Python π string formatting.
I have been preaching π that f-strings are the best string formatting alternative.
Then comes the string method `.format`.
And only then, %-formatting.
Here is a thread π§΅ comparing the 3 π
In its most basic form,
π %-formatting uses % and a letter inside the string
π `.format` replaces sequences of {} with the data
π f-strings use {} to insert the data _inside_ the string
Here is how it looks like π
An undervalued feature of string formatting is that you can easily determine whether your data should be formatted with its string (str) or with its representation (repr).