Python Socket Programming for Network Communication

Understanding HTTP, Socket, TCP, and UDP Concepts

The five-layer network model outlines the communication process between servers. HTTP implements various functions by adhering to speciifc protocol specifications.

Socket acts as an abstraction layer, allowing direct interaction with TCP and UDP without dealing with HTTP protocols.

TCP (Transmission Control Protocol) is a connection-orineted, reliable, byte-stream transport layer protocol. It requires establishing a connection before data transmission, similar to making a phone call. UDP (User Datagram Protocol) is a connectionless, simple transport layer protocol that sends datagrams without guaranteeing delivery.

Implementing Socket-Based Client-Server Communication

This example demonstrates a basic chat application supporting multiple concurrent clients.

Server Implementation:

import socket
import threading

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8000))
server_socket.listen(5)

def handle_client(client_socket, address):
    while True:
        received_data = client_socket.recv(1024)
        if not received_data:
            break
        print(f"Received: {received_data.decode('utf-8')}")
        response = input("Reply: ")
        client_socket.send(response.encode('utf-8'))

while True:
    client_sock, client_addr = server_socket.accept()
    thread = threading.Thread(target=handle_client, args=(client_sock, client_addr))
    thread.start()

Client Implementation:

import socket

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

while True:
    message = input("Message: ")
    client_socket.send(message.encode('utf-8'))
    reply = client_socket.recv(1024)
    print(f"Server replied: {reply.decode('utf-8')}")

Simulating HTTP Requests Using Raw Sockets

This code demonstrates how to fetch web content using sockets directly, bypassing higher-level libraries.

import socket
from urllib.parse import urlparse
import time

def fetch_url(url):
    parsed = urlparse(url)
    host = parsed.netloc
    path = parsed.path or '/'
    
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((host, 80))
        request = f"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"
        sock.send(request.encode('utf-8'))
        
        buffer = []
        while True:
            chunk = sock.recv(4096)
            if not chunk:
                break
            buffer.append(chunk)
        
        raw_response = b''.join(buffer).decode('utf-8')
        html_content = raw_response.split('\r\n\r\n', 1)[1]
        return html_content

if __name__ == '__main__':
    start = time.time()
    for i in range(20):
        url = f"http://example.com/resource/{i}"
        fetch_url(url)
    print(f"Duration: {time.time() - start:.2f} seconds")

Tags: python Socket Programming tcp HTTP udp

Posted on Sun, 20 Sep 2026 16:18:54 +0000 by xeross