It is late and I decided to code a simple TCP server in pure Python. But what is a server? Anything that receives connection from other computers called clients is called a server. This server keeps the connection open and waits for clients to connect. Python is rich in libraries and the socket library will help us to create the server. What is a socket? A socket is one end-point of a two-way
communication link between two programs running on the network. If you have previous experience with sockets in C programming language you understand very well what I am trying to explain. When you watch a movie online, a socket is created in the client side which connects to the server that does the streaming. Sockets are necessary and powerful. The base of the server we will learn to write is the socket and to create and use sockets in python we must import the socket library like shown in Figure 1. To create the server we need to create a socket, listen for incoming connections, accept clients when they try to connect and send and receive data. Once you create a socket object you can use functions to operate with it.
Figure 1 – Importing socket library
Since we need a constant connection between the client and the server we should create a socket_stream like shown in Figure 2.
Figure 2 – Creating the socket
Now it is time to use this socket. We should open a port where we want the client to connect the server. The socket we created is assigned to the socket_stream variable so now everytime we want to use the socketwe can refer to that variable. How do we put the ‘server’ in listening mode? We use the ‘listen()’ method to set up start TCP listener. This is the part one of our Python for Networking series. It is very easy to follow because we explain things step by step and don’t do much coding in this part. I prefer to take it slow so we can build strong skills and and I am sure that you guys will understand very well the next article of these series.