You’re the Expert!

Build mountain with each pebble 🧗

Topics | Stepping Stones

🌐 Network Programming in Python

Network programming is the practice of writing programs that communicate with other programs or systems across a
computer network (like the internet or local networks). Python makes this easy using the built-in socket module and
other libraries.


🧠 Why Network Programming?

Network programming allows you to:

  • Create chat apps
  • Build web servers or clients
  • Connect devices (IoT)
  • Transfer files over LAN/Internet

Python supports both low-level (sockets) and high-level (HTTP, FTP, etc.) networking.


🔌 The socket Module – Core of Network Programming

The socket module allows communication between two nodes using the TCP/IP protocol.

🔧 Creating a Simple Server

import socket

# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind to localhost and port
server_socket.bind(('localhost', 12345))

# Listen for incoming connections
server_socket.listen()

print("Server is listening on port 12345...")

# Accept a connection
client_socket, addr = server_socket.accept()
print(f"Connected to {addr}")

# Receive and send data
data = client_socket.recv(1024).decode()
print("Client says:", data)

client_socket.send("Hello from server!".encode())

# Close sockets
client_socket.close()
server_socket.close()

💬 Creating a Simple Client

import socket

# Create client socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to server
client_socket.connect(('localhost', 12345))

# Send and receive
client_socket.send("Hello from client!".encode())
data = client_socket.recv(1024).decode()
print("Server says:", data)

# Close
client_socket.close()

📡 How TCP/IP Communication Works

Step Description
Server socket Listens for connections
Client socket Connects to the server
Data Transfer Via send() and recv() methods
Close Connection Using close() on sockets

🔁 Continuous Chat Between Server and Client

Server (Looped chat)

import socket

server_socket = socket.socket()
server_socket.bind(('localhost', 12345))
server_socket.listen()

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

while True:
    data = conn.recv(1024).decode()
    if data.lower() == 'bye':
        break
    print("Client:", data)
    reply = input("Server: ")
    conn.send(reply.encode())

conn.close()
server_socket.close()

Client (Looped chat)

import socket

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

while True:
    msg = input("Client: ")
    client_socket.send(msg.encode())
    if msg.lower() == 'bye':
        break
    data = client_socket.recv(1024).decode()
    print("Server:", data)

client_socket.close()

🕸 Higher-Level Networking (HTTP Requests)

Python also offers high-level libraries like requests.

import requests

response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())

⚙️ Common Socket Methods

Method Purpose
socket() Creates a new socket
bind() Binds socket to address
listen() Listens for incoming connections
accept() Accepts a connection
connect() Connects to a server
send()/recv() Send/receive data
close() Close the connection

🔐 UDP Socket Example (No connection, faster)

Server

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('localhost', 12345))

print("Waiting for data...")
while True:
    data, addr = sock.recvfrom(1024)
    print("Received:", data.decode())
    if data.decode().lower() == 'bye':
        break
sock.close()

Client

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
    msg = input("You: ")
    sock.sendto(msg.encode(), ('localhost', 12345))
    if msg.lower() == 'bye':
        break
sock.close()

✅ Summary

  • Python offers both low-level (sockets) and high-level (requests, urllib) libraries.
  • Communication involves server listening and client connecting.
  • TCP is connection-oriented, UDP is connectionless.
  • Use recv() and send() to exchange data.

📚 References
Python socket docs
Python requests library
GeeksForGeeks – Python Networking


Created with ❤️ by Pynfinity

Create Blogs