Socket Programming in Python

Socket Programming in Python

Socket programming in Python allows applications to communicate using networks, supporting data transmission between processes on various machines.  Understanding socket programming is important for designing chat applications, online services, and real-time monitoring tools.  This article explores socket programming in Python, covering fundamental principles, implementation, and practical applications.

Table of Contents

What is a Socket?

A socket is an endpoint for communication between two programs running on the same or different machines. It enables inter-process communication (IPC) by establishing a connection through named contact points.

Messenger apps, such as WhatsApp, use sockets to transmit and receive messages between users. Sockets enable data transfer via the operating system’s built-in networking capabilities. There are two major types of sockets:

  • Server sockets: Listen for and accept incoming connections.
  • Client sockets: Initiate a connection to a server.

What is Socket Programming in Python?

Socket programming is a technique for connecting two applications, or nodes, on a network by using sockets as endpoints for transferring and receiving data. It is a key networking concept that allows programs to communicate data over local and remote networks.

In Python, the socket module contains functions for generating and maintaining sockets. Below is an example of designing a basic socket:

import socket
obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  • AF_INET specifies that the socket will use IPv4 addresses.
  • SOCK_STREAM indicates a TCP connection.

Why is Socket Programming required?

Sockets are helpful in both standalone and networked applications. Sockets enable you to share information between processes on the same system or over a network, assign work to the most efficient machine, and conveniently access centralized data.

  1. Platform Independent: 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.

How to Create a Server Socket?

A server socket listens for client connections and responds accordingly. Below is an example of creating a basic server in Python:

Step 1 – Create a Server Socket

import socket

host = '127.0.0.4' # localhost
port = 22222 # Choose an available port

server_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Step 2 – Bind the Server to an Address and Port

server_obj.bind((host, port))

Step 3 – Start Listening for Connections

server_obj.listen(5)
print(f"Server is listening on {host}:{port}")

Step 4 – Accept and Communicate with Clients

while True:
try:
client_obj, client_address = server_obj.accept()
print(f"Accepted connection from {client_address}")
info = "Information for the client"
client_obj.send(info.encode('utf-8'))
client_obj.close()

Step 5 – Handle Errors and Shutdown

    except KeyboardInterrupt:
print("\nServer is shutting down.")
break
except Exception as exp:
print(f"An error occurred: {str(exp)}")

server_obj.close()

To test the server, use telnet:

  • Run $ python server.py in a terminal.
  • In another terminal, run $ telnet localhost 22222.

Creation of a Client Socket in Python

A client socket connects to a server and exchanges data. Below is an example:

Step 1 – Create a Client Socket

client_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Step 2 – Connect to the Server

client_obj.connect((server_host, server_port))

Step 3 – Receive Data from the Server

data = client_obj.recv(1024)  # Receive up to 1024 bytes

Step 4 – Handle Exceptions

except ConnectionRefusedError:
print("Connection was refused.")
except Exception as exp:
print(f"An error occurred: {str(exp)}")

Step 5 – Decode and Print the Data, Close the Socket

print(f"Received message from server: {data.decode('utf-8')}")
finally:
client_obj.close()

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.

1. Server-side Code

Step 1- Create a Server Socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Step 2 – Bind the Server to an Address and Port

server_socket.bind(('localhost', 12345))

Step 3 – Start Listening for Connections

server_socket.listen(5)
print("Chat server is listening...")

Step 4- Define the handle_client Function

def handle_client(client_socket):
while True:
try:
data = client_socket.recv(1024)
if not data:
break
for client in clients:
client.send(data)
except:
break
clients.remove(client_socket)
client_socket.close()

Step 5 – Accept Client Connections and Create Threads

while True:
client_socket, client_address = server_socket.accept()
print(f"Accepted connection from {client_address}")
clients.append(client_socket)
client_thread = threading.Thread(target=handle_client, args=(client_socket,))
client_thread.start()

2. Client-side Code

Step 1 – Create a Client Socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))

Step 2 – Define the receive_messages Function

def receive_messages():
while True:
try:
data = client_socket.recv(1024)
print(data.decode())
except:
break

Step 3 – Start the Thread to Handle Receiving Messages

receive_thread = threading.Thread(target=receive_messages)
receive_thread.start()

Step 4 – Send Messages to the Server

while True:
message = input()
client_socket.send(message.encode())

This chat server allows multiple clients to connect and exchange messages in real time.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

Socket programming is integral to modern networking applications, including IoT, cloud computing, and AI-driven systems. While high-level frameworks often abstract socket management, understanding the underlying mechanics enhances a developer’s ability to build efficient network applications.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort Starts on: 15th Apr 2025
₹20,007
Cohort Starts on: 22nd Apr 2025
₹20,007

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.