What are Sockets?
A socket is an endpoint for sending and receiving data across a network. Sockets enable communication between devices, applications, or servers over the TCP/IP protocol. Python provides the socket
module to create and manage sockets for networking.
Types of Sockets
- Stream Sockets (TCP) – Reliable, connection-oriented communication.
- Datagram Sockets (UDP) – Unreliable, connectionless communication.
- Raw Sockets – Direct packet-level communication (used in security & network analysis).
Creating a Simple TCP Server and Client in Python
Step 1: Import the Socket Module
The socket
module provides the necessary functions for working with sockets.
import socket
TCP Server Example
A TCP server listens for incoming client connections and responds to their requests.
Step 2: Create a TCP Server
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP socket
server_socket.bind(("127.0.0.1", 8080)) # Bind to localhost and port 8080
server_socket.listen(5) # Allow up to 5 connections
print("Server is listening...")
while True:
client_socket, client_address = server_socket.accept() # Accept connection
print(f"Connection established with {client_address}")
client_socket.send(b"Hello from Server!") # Send a message
data = client_socket.recv(1024) # Receive data
print("Received:", data.decode())
client_socket.close() # Close client connection
The server listens for connections and communicates with the client.
TCP Client Example
A TCP client connects to the server and sends data.
Step 3: Create a TCP Client
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 8080)) # Connect to the server
message = client_socket.recv(1024) # Receive data from the server
print("Server says:", message.decode())
client_socket.send(b"Hello from Client!") # Send a message
client_socket.close() # Close the connection
The client connects to the server and exchanges messages.
UDP Server and Client Example
UDP is faster but does not guarantee message delivery.
UDP Server
import socket
udp_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_server.bind(("127.0.0.1", 8081)) # Bind to port 8081
print("UDP Server is listening...")
while True:
data, addr = udp_server.recvfrom(1024) # Receive message
print(f"Received from {addr}: {data.decode()}")
udp_server.sendto(b"Hello from UDP Server!", addr) # Send response
UDP Client
import socket
udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_client.sendto(b"Hello from UDP Client!", ("127.0.0.1", 8081)) # Send message
response, _ = udp_client.recvfrom(1024) # Receive response
print("Server says:", response.decode())
udp_client.close()
UDP is useful for real-time applications like gaming and video streaming.
Handling Multiple Clients with Threads
A server can handle multiple clients using multithreading.
Multi-Client TCP Server
import socket
import threading
def handle_client(client_socket, client_address):
print(f"Connection from {client_address}")
client_socket.send(b"Hello from Multi-Threaded Server!")
data = client_socket.recv(1024)
print(f"Received from {client_address}: {data.decode()}")
client_socket.close()
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("127.0.0.1", 8082))
server_socket.listen(5)
print("Server is listening for multiple clients...")
while True:
client_socket, client_address = server_socket.accept()
thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
thread.start()
This allows handling multiple clients simultaneously.
Sending Large Data using Sockets
When sending large amounts of data, it is best to split data into chunks.
def send_large_data(sock, data):
chunk_size = 1024
for i in range(0, len(data), chunk_size):
sock.send(data[i:i+chunk_size])
Ensures efficient transmission of large files or messages.
Applications of Sockets
✔ Web servers – Handle HTTP requests
✔ Chat applications – Real-time messaging
✔ File transfer – Sending & receiving files over networks
✔ IoT – Communication between smart devices
✔ Cybersecurity – Penetration testing & network scanning