Now that we finished writing the TCP server it is time to write a simple client which will connect to the server. It is very simple to create our client with the socket library and now we have enough knowledge to do it. Our client will open a connection to our server on 113 port, the port in which our server is listening. One important thing you should know about sockets is that they are like IO objects, you can read from a socket like you read from IO object. After you finish reading make sure you close the socket with socket’s close() method. Open a new file with the vim text editor and name it client.py or anyname.py. We start with the shebang line and we import the socket library the same way we did with the TCP server. After that we create our socket object and assign it to a variable like shown in Figure 1.
We need the server name we want to connect and the port in which the server is listening on. I used the 113 port for the server when I create it so this is the port we will use for the connection. Now create two variables, server_name and port_number; the first one is for the server and the second is for the port number.
We will run both scripts on our local machine, that’s why I assigned server_name variable to localhost. Nothing happens if we run the client.py script, it is not finished yet.
We use the connect() method to create a connection with the server and use the recv() method to receive data from server like shown in Figure 4. If you remember from the previous article, when we wrote the server, we used send() method to send data to clients that connect to our server. You can see that we use recv() in the client side to receive data sent from the server; client can use send() to send data but this is not the purpose of this article. We use the print statement to print the data we get from server. Figure 4 shows it all.
It is easy and beautiful, isn’t it? You feel something special when the client connects to the server when you do this for the first time, at least this is what I felt. Time for some magic. Open two terminal windows and change directory to the folder where you have your client and your server. Run the server in one terminal window like shown in Figure 5.
Now run the client in the other terminal window like shown in Figure 6.
Great! ‘You connected’ is printed on the client screen. This is data from the server. As you can see from Figure 6 our server does not close the socket, it listens day and night. Remember the ‘while True’ conditional statment from the previous article.