Table of contents
1.
Introduction
2.
Create Socket
3.
Connection with a server
4.
Server - Client Program
4.1.
Server
4.2.
Client
5.
Python socket Module
6.
Python File Transfer with Socket Module
6.1.
Example Code
7.
The Python socketserver Module
7.1.
Key Classes in socketserver
8.
Frequently asked questions
8.1.
What are sockets in programming in Python?
8.2.
What is socket programming?
8.3.
What is socket programming in Django?
9.
Conclusion
Last Updated: Aug 28, 2025
Easy

Socket Programming In Python

Introduction

Socket programming in Python enables communication between devices over a network. It forms the backbone of many network-based applications, such as chat programs or file transfer protocols. Using sockets, Python allows developers to create client-server connections and send/receive data. 

Socket Programming In Python

In this article, we wll learn the basics of socket programming in Python, including how to set up client and server sockets, handle connections, and explore practical examples for better understanding.

Create Socket

Socket programming needs a library in Python to create sockets and work with them.

import socket

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

We have imported the socket library by using import socket in our program. There are two parameters needed for creating a socket.

  1. AF_INET represents the ipv4 address family.
  2. SOCK_STREAM describes the connection-oriented TCP protocol.

Connection with a server

In this example, we connect to the Google server. We will see what our program does step by step.

  • First, we have imported the socket library to use sockets in our program.
  • Then we try to create the socket. If an error occurs in creating the socket, it is handled by try and except block.
  • After that, we get the IP of the Google server.
  • In the end, we connect to a Google server using the connect function
import socket  
import sys
try:
    skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print ("Socket created")
except socket.error as e:
    print ("socket creation failed with error %s" %(e))
# default port for socket
port = 80
try:
    # get the ip of google server.
    hostip = socket.gethostbyname('www.google.com')
except socket.gaierror:
    # this means that we can not resolve the host
    print ("there is an error resolving the host")
    sys.exit()
# connecting to the server
skt.connect((hostip, port))
print ("the socket successfully connected to google")
You can also try this code with Online Python Compiler
Run Code

Output

Socket created

the socket successfully connected to google 

on port == 173.194.40.19

Now, we will learn to establish a connection between client and server using sockets.

You can compile it with online python compiler.

Server - Client Program

Server

  • A server uses the bind() method to bind to a specific port and IP so that it can listen to the incoming requests on that IP and port. 
  • After binding to a specific port server will listen to that port using listen method(). The listen method() allows the server to listen to incoming connections.
  • After that, we connect with the client using the accept() method.
  •  And at the end, we end the connection with the client using the close() method.

Example

In this example, we will discuss the flow of the server program step by step.

  • First of all, we have imported the socket library to use sockets in our program.
  • After that, we made a socket object and reserved a port on our pc.
  • After that, we bind our server to that specific port. Passing an empty string implies that the server can also listen to incoming connections from other computers too. If we pass 127.0.0.1, it will listen to only those calls that are made within the local computer.
  • Then, we put the server into listening mode. 5 here represents that 5 connections will keep waiting if the server is busy and the 6th socket tries to connect with the server, then the connection is refused.
  • At last, we used a while loop and started to accept all incoming connections from the client and close those connections after a thank you message to all connected sockets.

To run the client-server program first, we need to run the server program. We will type python server.py  in the terminal to run the server program

# import the socket library
import socket            
# create a socket object
skt = socket.socket()        
print ("Socket created")
# reserve a port on the computer in our
# case it is 12345, but it can be anything
port = 12345               
# Next, bind to the port
# we have not typed any IP in the IP field
# instead, we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
skt.bind(('', port))        
print ("socket binded to %s" %(port))
# put the socket into listening mode
skt.listen(5)    
print ("socket is listening")            
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish a connection with the client.
  c, addr = skt.accept()    
  print ('Got connection from', addr )
  # thank you message sent to the client. encoding to send byte type.
  c.send('Thank you for connecting'.encode())
  # Close the connection
  c.close()
  # Breaking the loop
  break
You can also try this code with Online Python Compiler
Run Code

Output

Socket created

socket binded to 12345

socket is listening

Client

After creating a server, we need a client to interact with the server.

  • At first, we made a socket object.
  • Then we connect to the localhost on port number 12345 (the port to run the server), and at last, we receive data from the server, and finally, the connection is closed.
  • Now, we will save the code in a file as client.py and run it in the terminal after starting the server script.

To run the client program, we type python client.py in the terminal.

Example

# Import socket library
import socket            
# Create a socket object
skt = socket.socket()        
# Choose a port for connection
port = 12345               
# connect to the server on your local computer
skt.connect(('127.0.0.1', port))
# receive data from the server and decode it to get the string.
print (skt.recv(1024).decode())
# close the connection
skt.close()    
You can also try this code with Online Python Compiler
Run Code

Output

Thank you for connecting

Now, let us move to the FAQs section to clear your doubts regarding socket programming.

Python socket Module

The Python socket module provides the necessary tools to create network connections. It offers both client and server functionality for communication over the internet or local networks. By using the socket module, Python developers can build server-client systems, send/receive data, and handle different protocols like TCP/IP or UDP. This module is crucial for building network applications such as web servers, chat applications, and more.

Python File Transfer with Socket Module

Python's socket module allows you to transfer files between a client and server over a network using a socket connection. This process involves setting up a communication channel through which data (in this case, files) can be sent and received.

Here’s how file transfer works in Python using the socket module:

Server Side:

  • The server listens on a specific port for incoming client connections. Once a connection is established, the server opens the file to be sent and reads its content.
     
  • The file is typically divided into smaller chunks (such as 1024 bytes at a time) to avoid overwhelming the network. These chunks are sent one after the other to the client via the socket connection.
     
  • After successfully sending the file, the server closes the socket connection.

Client Side:

  • The client connects to the server by specifying the IP address and port number of the server.
     
  • Upon establishing a connection, the client receives the chunks of the file. These chunks are collected and written to a new file on the client’s local system.
     
  • Once the entire file is received, the client can store the file in the desired location and close the connection.

Example Code

Server Code:

import socket
def send_file(filename, host, port):
   s = socket.socket()
   s.bind((host, port))
   s.listen(1)
   print("Waiting for connection...")
   client, addr = s.accept()
   print(f"Connection established with {addr}")
   
   with open(filename, 'rb') as file:
       data = file.read(1024)
       while data:
           client.send(data)
           data = file.read(1024)
   
   print(f"File {filename} sent successfully.")
   client.close()
send_file('example.txt', 'localhost', 12345)


Client Code:

import socket
def receive_file(filename, host, port):
   s = socket.socket()
   s.connect((host, port))
   with open(filename, 'wb') as file:
       data = s.recv(1024)
       while data:
           file.write(data)
           data = s.recv(1024)
   
   print(f"File {filename} received successfully.")
   s.close()
receive_file('received_example.txt', 'localhost', 12345)

The Python socketserver Module

The socketserver module in Python simplifies the process of writing network servers by providing a framework for handling incoming socket connections. It offers several classes that can be extended to create servers for different protocols (TCP, UDP, etc.), making it easier to write multi-threaded or multi-process networked applications.

The module works by creating a server that listens for client connections on a specified port. When a connection is established, the server processes the request using a request handler, which is a class that inherits from BaseRequestHandler. The request handler is responsible for handling the connection, receiving and sending data to the client.

Key Classes in socketserver

 

  1. TCPServer: This class provides the functionality to create a TCP server. It uses the standard TCP protocol to communicate with clients.
     
  2. UDPServer: Similar to TCPServer, but for handling UDP connections. It works with the connectionless UDP protocol.
     
  3. BaseRequestHandler: This is the base class for handling requests. It processes each connection in a specific manner defined by the user.
     
  4. ThreadingMixIn: This class can be used to make a server handle each request in a new thread, improving concurrency.

Frequently asked questions

What are sockets in programming in Python?

Sockets in Python are endpoints for sending or receiving data across a network. They allow communication between different devices over a network by providing an interface for creating server-client applications.

What is socket programming?

Socket programming is a method used for creating networked applications. It involves using sockets to establish connections, transmit data, and manage communication between devices or processes over the internet or local networks.

What is socket programming in Django?

Socket programming in Django involves using Django to create real-time web applications by enabling communication between clients and servers via WebSockets or similar socket-based protocols for live updates, such as chat applications or notifications.

Conclusion

In this article, we learned about socket programming in Python, including the basics of socket communication, how to transfer files using sockets, and the use of the socketserver module for building server applications. 

Also read : 

 

Live masterclass