There is a full-fledged approach to connect two or more sockets(nodes) on a network for communication. When it comes to programming, it is called Socket Programming. These sockets or nodes form a client-server relationship between them. The listener socket becomes server while the client requests to the server or the listening socket.

This post is a guide for the Pythonistas who are looking to build their own client-server applications. There is a lot to cover when we talk about sockets and networks. But, this post won’t be too overwhelming for you. Let’s start then!

What are sockets?

When the internet boomed in the 90s, a new area of programming took birth at that time — network programming it was. The internet was not only about websites and browsers. Web applications and client-server applications were starting to take off. And, those are the most common socket applications nowadays.

In Python, we get a whole module i.e **socket() **which makes the path easier for building a client-server application.

FYI, this socket() module is based on Berkeley sockets API.

socket() module

Now that you are aware of why you will be using socket programming in Python. The first step would be to import the module and create a socket object.

import socket
socket.socket(socket.SOCK_STREAM)

In the above code, I have also defined the socket type i.e socket.SOCK_STREAM which means that the object will be using TCP(Transmission Control Protocol).

You can also go for UDP(User Datagram Protocol) using socket.SOCK_DGRAM . But, TCP is more reliable than UDP and data can be out-of-order for the receiver at times.

In the below image, you can take a look at the flow of socket API calls. Also, how client and server API calls differ from each other.

Technically, the client-side calls connect() try to connect with the server-side. The server calls listen() to listen to the connection from the client and accept it by callingaccept() .

After the connection is built, data is sent/received by both the sides by calling send() or recv() . To close the connection, a function close() is called.

#python #programming #networking #web-development #coding #socket

Socket Programming: Using Socket() Module in Python
2.00 GEEK