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)
TCP Client (client.py)
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.
Sending POST Requests
POST requests are used to submit data to a server (e.g., submitting a form).