Socket Programming: Using Socket() Module in Python

Communicate with nodes using socket()

Vishal Sharma
The Startup
4 min readJul 4, 2020

--

Photo by Marvin Meyer on Unsplash

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.

Socket Programming — Wiki

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.

Programming client-side

Let’s say, we want to send a connection request to a server. Here’s how we can do it.

import socketserver_host = '127.0.0.1'  #server's IP
server_port = 65432 #server port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((server_host, server_port))
s.sendall(b'Hello!, world')
data = s.recv(256)

print('Received', repr(data))

Our code is basically trying to connect to the server’s IP and a specific port. And, then it wants to send a text to the server. If the server replies, it will be stored in the data variable and will be printed.

Programming server-side

Client-side is very simple to program. It just needs to send a request and store a received message. But, on the server-side, there is a lot of stuff happening.

#!/usr/bin/env python3
import socket

server_host = '127.0.0.1'
server_port = 65432 # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((server_host, server_port))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)

The above code does a lot! It calls a socket object and then listens to specific IP and port on the node. It then listens to the request, creates the connection, and accepts the specific address.

After the connection is built, an infinite-loop is run until the whole data is received by the server. Whatever data is read is echoed back using the sendall() method. When the whole transmission completes, the connection is closed.

Running the scripts

For building the connection, you will have to run the server script first on the terminal. It will keep on running until the client does not request for a connection. So, you will have to run the client script on the other terminal window.

Hence, your output will look like this on both the scripts.

Server: Address tuple printed that consists of IP and port number.

Client: Message echoed by server saying it got the message.

Summary

In this post, I have talked about sockets and socket programming in Python. And, how you can create a network of nodes and communicate.

  • Socket Introduction
  • socket() module in Python
  • Building a network connection using a client and a server script

Peace!

--

--