Sockets, according to Wikipedia, are internal endpoints for sending or receiving data with a node on a computer network. I'd describe them as channels for sending and receiving data over a networking protocol.
You can find the official documentation here. This page will however suffice in getting you started with socket programming and fundamentals.
The command you can run is
pip install sockets
This will install the sockets library in the currently sourced Python interpreter.
There is a basic diagram that you should remember. It covers about 50% of sockets and is very helpful in understanding the flow. The figure is on the right. So essentially here's the theory you need to understand:
A few extra things that are good to know:
This will create a server node that after getting initialized will connect to a client node, print whatever is sent, exit when connection is broken and no more data is received. Let me show you the code first, I'll then follow up with an explanation for the code.
Here's what I've done step by step. Keep Figure 1 in mind and read through:
socket()
constructor.(ip_address, port_number)
for addressing.socket()
here.bind()
function. We pass it the full address (tuple as specified in family during initialization) on which the socket is to be hosted.bind()
here.listen()
function. The argument specifies backlog. Basically, how many connections can be handled in a queue before the socket refuses new connections.listen()
here.accept()
function. This will wait till a new connection is received and will return a tuple containing a new socket for the connection and the client's address (full address as specified in family during initialization).accept()
here.recv()
function. The argument provided is the buffer size (1024 bytes in this case).recv()
here.This is pretty much how you create a server that listens to a client.
Here we'll create a node that will connect to a server, send "Hello World" to the server and then exit (break connection). I'll show you the code first, then follow up with the explanation
Here's what I've done, step by step:
connect()
function. In the arguments, we provide the full address of the server node.connect()
here.sendall()
function. The data has to be in the form of bytes, so we parse a string using the utf-8 encoding standard.This is pretty much how you create a client that sends a message to the server.
I'll this time show you the code for both and then follow up with explanation. You're encouraged to understand what's happening first, before reading the explanation
Site under development
Please be patient and wait for more content to be uploaded