• Articles

Guide to Socket Programming in Python

Guide to Socket Programming in Python

Socket programming in Python combines network communication and Python knowledge to build programs that can connect over networks. To help you understand how computer programs chat with each other over the internet, we will discuss the various aspects of socket programming in this post. So, if you’re eager to learn about inter-program or interprocess communication, dive in!

Table of Contents

Want to learn Python in detail? Watch this video led by industry experts for gaining in depth knowledge:

Video Thumbnail

What is a Socket?

What is a Socket?

We can define a socket as a quick connection that allows the exchange of information between two processes on the same machine or different machines over a network. By creating named contact points between which the communication takes place, the socket mechanism offers a form of inter-process communication (IPC).

For example, if one WhatsApp user wants to send a message to another WhatsApp user, this will be possible by creating a socket. Sockets allow the transfer of data between two processes using the built-in mechanisms of the operating system and hardware. There are two types of sockets: server sockets and client sockets.

What is Socket Programming in Python

Sockets are essential for establishing connections and facilitating communication between two or more nodes over a network. Web browsing is an example of socket programming. The user requests the web server for information, and the server processes the request and provides the data. In Python, for creating a simple socket, the socket library is imported.

import socket
obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Here, an object of the socket class is created, and two parameters are passed to it. The first parameter, i.e., AF_INET, refers to the ipV4 address family, meaning only ipV4 addresses will be accepted by the socket. The second parameter, SOCK_STREAM, means connection-oriented TCP protocol, making the socket available for TCP protocol only.

Preparing for Job Interview? Refer to Python Interview Questions to excel in your Interviews!

Why is Socket Programming required?

Why is Socket Programming required?

Sockets allow for interprocess communication between processes that are executing on the same machine or on distinct machines. Applications must coordinate activities and exchange data through interprocess communication.

  1. Platform Independence: Sockets offer a method of building network applications that are independent of platforms. Python, C, Java, and other programming languages can be used by developers to create socket code that will run on a variety of operating systems
  2. Versatility: Sockets can be utilized in a wide range of network communication contexts, from straightforward data exchange to intricate client-server communications.

Elevate your career with our free Python course and earn a valuable certification to showcase your expertise!

How to Create a Server Socket?

How to Create a Server Socket?

In the following program, we demonstrate the creation of a server socket. 

import socket
# Defining the host and port on which the server will listen
host = '127.0.0.4'  # localhost
port = 22222  # Choose an available port
# Creating a socket object
server_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the host and port
server_obj.bind((host, port))
# Listen for incoming connections
server_obj.listen(5)  # Accept up to 5 connections
print(f"Server is listening on {host}:{port}")
while True:
Try:
# Accept a connection from a client
client_obj, client_address = server_obj.accept()
print(f"Accepted connection from {client_address}")
# Send data the connected client
info = “information for the client"
client_obj.send(info.encode('utf-8'))
# Close the client socket
client_obj.close()
except KeyboardInterruption:
print("\nServer is shutting down.")
break
except Exception as exp:
print(f"An error occurred: {str(exp)}")
# Close the server socket
server_obj.close()

Here, a single system is playing the role of both a server and a client. The server listens for requests from the client. The server can only handle a limited number of requests at a time. If, for some reason, it is unable to accept a request, then the ‘except’ block will be executed. After approving a request, the server provides the required information to the client before closing the connection.

To check whether the server is working, we can use telnet. The following steps are used for this purpose:

  1. Open a terminal, type $python server.py, and keep it open.
  2. Open another terminal and type $ telnet localhost 22222.

Here, 22222 is the port number.

Discover the Python tutorial that will ignite your coding journey and empower you to create, automate, and innovate.

Get 100% Hike!

Master Most in Demand Skills Now!

Creation of a Client Socket in Python

Up to this point, we have created a server socket. Now, we will need a client socket too. For creating a client socket for a previously created server, we need the following code:

import socket
# Define the server's host and port
server_host = '127.0.0.4'  # localhost
server_port = 22222 # the same port the server is listening on
# Creating a socket object for the client
client_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connecting to the server
client_obj.connect((server_host, server_port))
# Receiving data from the server
data = client_obj.recv(1024)  # Receive up to 1024 bytes of data
# Decoding and printing the received information
info = data.decode('utf-8')
print(f"Received message from server: {info}")
except ConnectionRefused:
print("Connection was refused.")
except Exception as exp:
print(f"An error occurred: {str(exp)}")
# Close the client socket
client_obj.close()

Here, we created two variables, server_host and server_port, to match the host and port of the server to which we want to connect. Then we created a socket object named client_obj. In the next step, client_obj is used to connect to the server using the connect() method. 

After receiving it, the data is decoded. Here, only up to 1024 bytes of data can be received.If there is an issue connecting to the server, then only the except block will be executed. It is important to note that first the server-side program will be executed, then the client-side program, because to process the client’s request, the server should be active first.

Know about Python developer roles and responsibilities to begin a career as a Python developer.

Example of Socket Programming in Python

We’ll create a basic chat server that can handle multiple clients as an example of socket programming in Python. Each client can send messages to the server, and the server will broadcast those messages to all connected clients.

On the server side, the following program will be created:

import socket
import threading
# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Bind the socket to a specific address and port
server_address = ('localhost', 12345)
server_socket.bind(server_address)
# Listen for incoming connections
server_socket.listen(5)
print("Chat server is listening for incoming connections...")
# List to keep track of connected clients
clients = []
# Function to handle client connections
def handle_client(client_socket):
while True:
try:
# Receive data from the client
data = client_socket.recv(1024)
if not data:
break
# Broadcast the received message to all clients
for client in clients:
client.send(data)
except:
break
# Remove the disconnected client from the list
clients.remove(client_socket)
client_socket.close()
while True:
# Accept a connection from a client
client_socket, client_address = server_socket.accept()
print(f"Accepted connection from {client_address}")
# Add the client socket to the list
clients.append(client_socket)
# Create a thread to handle the client
client_thread = threading.Thread(target=handle_client, args=(client_socket,))
client_thread.start()

On the client side, we will write the following program:

import socket
import threading
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
server_address = ('localhost', 12345)
client_socket.connect(server_address)
# Function to receive and print messages from the server
def receive_messages():
while True:
Try:
data = client_socket.recv(1024)
print(data.decode())
except:
break
# Start a thread to receive messages
receive_thread = threading.Thread(target=receive_messages)
receive_thread.start()
# Send messages to the server
while True:
message = input()
client_socket.send(message.encode())

Conclusion

Socket programming is an important part of computing and networking, as it plays a key role in IoT, cloud computing, 5G networks, and artificial intelligence. As technology evolves and connectivity expands, socket programming enables efficient communication and data exchange between different devices and platforms.

In contemporary practices, the direct use of sockets is less common, as higher-level libraries and frameworks typically manage them. However, delving into socket functionality remains beneficial, enhancing developers’ and data scientists’ overall understanding of application mechanics, making it a valuable skill to possess.

Course Schedule

Name Date Details
Python Course 30 Nov 2024(Sat-Sun) Weekend Batch View Details
07 Dec 2024(Sat-Sun) Weekend Batch
14 Dec 2024(Sat-Sun) Weekend Batch