Skip to content

Python Network Programming

Network programming allows computers to communicate with each other over a network. Python provides several powerful libraries that make creating client and server applications relatively straightforward. This chapter will introduce two core network programming modules: socket for low-level network communication, and requests for high-level HTTP communication.

Core Concepts

  • Socket: Is the cornerstone of network communication. You can think of it as an endpoint for a network connection, like a telephone socket. Two computers need to establish a connection through sockets to exchange data.
  • IP Address: Unique identifier for each computer on a network (e.g., 192.168.1.1).
  • Port: A 16-bit number (0-65535) used to identify a specific application or service on a computer. For example, HTTP service typically runs on port 80, and HTTPS on port 443.
  • Protocol: Set of rules controlling how data is transmitted over a network. The most common are TCP and UDP.
    • TCP (Transmission Control Protocol): A connection-oriented, reliable protocol. It ensures data arrives in order and without errors. Suitable for scenarios requiring high reliability, such as file transfers and web browsing.
    • UDP (User Datagram Protocol): A connectionless, unreliable protocol. It simply does its best to send data but doesn't guarantee that data will arrive or arrive in order. Suitable for scenarios where speed is more important than reliability, such as video streaming and online gaming.

socket Module: Low-level Network Programming

The socket module provides access to low-level socket interfaces. Below is an example of a simple TCP server and client.

TCP Server (server.py)

python
import socket

# 1. Create a socket object
# AF_INET means using IPv4 addresses
# SOCK_STREAM means using TCP protocol
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 2. Bind IP address and port
host = '127.0.0.1' # Local address
port = 9999
server_socket.bind((host, port))

# 3. Start listening for client connections, 5 means maximum of 5 connections can queue
server_socket.listen(5)

print(f"Server is listening on {host}:{port}")

while True:
    # 4. Wait for and accept a new connection
    # accept() blocks the program until a client connects
    client_socket, addr = server_socket.accept()
    print(f"Received connection from {addr}")

    # 5. Send message to client
    # Strings need to be encoded to bytes
    message = 'Welcome to the server!' + "\r\n"
    client_socket.send(message.encode('utf-8'))

    # 6. Close client connection
    client_socket.close()

TCP Client (client.py)

python
import socket

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

# 2. Connect to server
host = '127.0.0.1'
port = 9999
client_socket.connect((host, port))

# 3. Receive data from server
# 1024 is the buffer size, meaning receive at most 1024 bytes at a time
data = client_socket.recv(1024)

# 4. Print received data (decode to string)
print(f"Received: {data.decode('utf-8')}")

# 5. Close connection
client_socket.close()

requests Library: High-level HTTP Programming

For most web-related development (such as calling APIs, scraping web pages), using socket directly is very cumbersome. requests is a very popular and user-friendly third-party library specifically designed for sending HTTP requests.

First, you need to install it: pip install requests

Sending GET Requests

GET requests are used to retrieve data from a server.

python
import requests

# Send a GET request to specified URL
response = requests.get('https://api.github.com')

# Check if request was successful (status code 200)
if response.status_code == 200:
    print("Request successful!")
    # response.json() automatically decodes the JSON-formatted response body into a Python dictionary
    data = response.json()
    print(data)
else:
    print(f"Request failed, status code: {response.status_code}")

Sending POST Requests

POST requests are used to submit data to a server (e.g., submitting a form).

python
import requests

url = 'https://httpbin.org/post'
# Data to be sent
payload = {'key1': 'value1', 'key2': 'value2'}

# Send POST request
response = requests.post(url, data=payload)

# Print response returned by server
print(response.json())

Content is for learning and research only.