Spex3
    

Python for Networking: Sockets & Requests πŸŒπŸ”—


    

    

Python provides powerful tools for network programming. Two key modules are:

πŸ”Ή Sockets – For low-level network communication (TCP, UDP).
πŸ”Ή Requests – For making HTTP requests (REST APIs, web scraping).

Let’s dive into both! πŸš€

1️⃣ Sockets – Low-Level Networking πŸ—οΈ
πŸ”Ή Sockets allow two computers to communicate over a network.
πŸ”Ή Supports TCP (reliable) & UDP (fast, no connection) protocols.

Installing the socket Module
βœ… No installation needed! socket is built into Python.

Basic TCP Server & Client
βœ… Server (Listens for Connections)

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("127.0.0.1", 12345)) # Bind to local IP & port
server_socket.listen(1)

print("Server is listening...")

conn, addr = server_socket.accept()
print(f"Connected by {addr}")

conn.sendall(b"Hello from Server!")
conn.close()
server_socket.close()
βœ… Client (Connects to Server)


import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 12345))

data = client_socket.recv(1024)
print("Received:", data.decode())

client_socket.close()

Key Features of Sockets

βœ” Low-level control over networking

βœ” Used in chat apps, game servers, and IoT

βœ” Can handle both TCP & UDP communication

2️⃣ Requests – Making HTTP Requests 🌐

πŸ”Ή Requests is a simple way to interact with web APIs.

πŸ”Ή Used for web scraping, API calls, automation.

Installing Requests


pip install requests
Making a Basic HTTP Request

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.json()) # Convert response to JSON
Sending Data via POST Request

import requests

data = {"title": "Python", "body": "Networking with Requests", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)

print("Response Code:", response.status_code)
print("Response Data:", response.json())
Handling Headers & Authentication

headers = {"Authorization": "Bearer YOUR_ACCESS_TOKEN"}
response = requests.get("https://api.example.com/data", headers=headers)
print(response.json())
Downloading a File with Requests

response = requests.get("https://example.com/file.pdf")
with open("downloaded_file.pdf", "wb") as file:
file.write(response.content)

Key Features of Requests

βœ” Easy to use for web requests

βœ” Supports authentication, headers, & sessions

βœ” Great for REST API interaction

3️⃣ Sockets vs. Requests – When to Use What?

Feature Sockets Requests

Type Low-level networking High-level HTTP requests

Use Case Real-time chat, game servers APIs, web scraping, automation

Protocol TCP, UDP HTTP, HTTPS

Ease of Use More complex Very simple


    Date: 2025-03-24 00:00:00.000000