SoFunction
Updated on 2025-04-13

Detailed explanation of Python network programming (common libraries, code cases, environment construction, etc.)

1. Commonly used libraries

  • socket: Provides a low-level network communication interface and supports TCP and UDP protocols.
  • asyncio: Used to write asynchronous network applications, support high concurrency.
  • http: Provides client and server implementation of the HTTP protocol.
  • requests: A simple and easy-to-use HTTP client library, often used to send HTTP requests.
  • websockets: A library used to implement the WebSocket protocol, supporting full duplex communication.

2. Detailed usage of the library

2.1 socket library

socketThe library is part of the Python standard library and provides a low-level network communication interface. Common methods include:

  • (): Create a new socket object.
  • (): Bind IP address and port.
  • (): Start listening to the connection.
  • (): Accepts a connection.
  • (): Connect to the remote server.
  • (): Send data.
  • (): Receive data.

2.2 asyncio library

asyncioThe library is used to write asynchronous network applications and supports high concurrency. Common methods include:

  • (): Run an asynchronous function.
  • asyncio.create_task(): Create a task.
  • (): Run multiple tasks concurrently.
  • (): Wait asynchronously for a period of time.

2.3 http library

httpThe library provides client and server implementations of the HTTP protocol. Commonly used modules include:

  • : Provides a simple HTTP server implementation.
  • : Provides a simple HTTP client implementation.

2.4 requests library

requestsThe library is a simple and easy-to-use HTTP client library, which is often used to send HTTP requests. Common methods include:

  • (): Send a GET request.
  • (): Send a POST request.
  • (): Send PUT request.
  • (): Send a DELETE request.

2.5 websockets library

websocketsThe library is used to implement the WebSocket protocol and supports full duplex communication. Common methods include:

  • (): Connect to the WebSocket server.
  • (): Send data.
  • (): Receive data.

3. Complete code case

3.1 Implementing TCP server and client using socket library

TCP server code:

import socket

def start_server():
    server_socket = (socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('127.0.0.1', 12345))
    server_socket.listen(5)
    print("Server listening on port 12345...")

    while True:
        client_socket, addr = server_socket.accept()
        print(f"Connection from {addr}")
        client_socket.send(b"Hello, client!")
        client_socket.close()

if __name__ == "__main__":
    start_server()

TCP client code:

import socket

def start_client():
    client_socket = (socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(('127.0.0.1', 12345))
    data = client_socket.recv(1024)
    print(f"Received: {()}")
    client_socket.close()

if __name__ == "__main__":
    start_client()

3.2 Implementing asynchronous TCP server and client using the asyncio library

Asynchronous TCP server code:

import asyncio

async def handle_client(reader, writer):
    data = await (100)
    message = ()
    addr = writer.get_extra_info('peername')
    print(f"Received {message} from {addr}")

    (b"Hello, client!")
    await ()
    ()

async def start_server():
    server = await asyncio.start_server(handle_client, '127.0.0.1', 12345)
    addr = [0].getsockname()
    print(f"Serving on {addr}")

    async with server:
        await server.serve_forever()

if __name__ == "__main__":
    (start_server())

Asynchronous TCP client code:

import asyncio

async def start_client():
    reader, writer = await asyncio.open_connection('127.0.0.1', 12345)
    (b"Hello, server!")
    await ()

    data = await (100)
    print(f"Received: {()}")

    ()
    await writer.wait_closed()

if __name__ == "__main__":
    (start_client())

3.3 Send HTTP requests using the requests library

import requests

def send_http_request():
    response = ('')
    print(f"Status Code: {response.status_code}")
    print(f"Response Body: {}")

if __name__ == "__main__":
    send_http_request()

3.4 Use the websockets library to implement WebSocket communication

WebSocket server code:

import asyncio
import websockets

async def handle_connection(websocket, path):
    async for message in websocket:
        print(f"Received: {message}")
        await (f"Echo: {message}")

async def start_server():
    async with (handle_connection, "localhost", 8765):
        await ()  # run forever

if __name__ == "__main__":
    (start_server())

WebSocket client code:

import asyncio
import websockets

async def start_client():
    async with ("ws://localhost:8765") as websocket:
        await ("Hello, server!")
        response = await ()
        print(f"Received: {response}")

if __name__ == "__main__":
    (start_client())

4. Dependencies

  • socket: Python standard library, no additional installation required.
  • asyncio: Python standard library, no additional installation required.
  • http: Python standard library, no additional installation required.
  • requests: Need to be installed, usepip install requests
  • websockets: Need to be installed, usepip install websockets

5. Environment construction

  • Python version: It is recommended to use Python 3.7 and above.
  • Virtual environment: It is recommended to usevenvorvirtualenvCreate a virtual environment.
  • Depend on installation: usepip install -r Install dependencies.

6. Things to note

  • Port conflict: Make sure that the port used is not occupied by other applications.
  • Exception handling: Various exceptions may be encountered during network programming, such as connection timeout, connection rejection, etc., and appropriate exception handling is required.
  • Resource release: Ensure that after using sockets, file descriptors and other resources, it is closed and released in time.

7. FAQ

  • Q: How to solve the problem of port occupied?

    • A: Can be usednetstat -anp | grep <port>(Linux) ornetstat -ano | findstr <port>(Windows) Find a process that occupies a port and terminates the process.
  • Q: How to deal with connection timeout?

    • A: Can be()or()Set timeout parameters in other methods, such as(5)or(url, timeout=5)
  • Q: How to improve the performance of network programming?

    • A: Asynchronous programming can be used (e.g.asyncio) to improve concurrency performance, or use multi-threading and multi-processing to handle multiple connections.

Summarize

Python provides a wealth of libraries and tools to support network programming from low-levelsocketTo a high levelrequestsandwebsockets, developers can choose the right tools according to their needs. Through reasonable exception handling, resource management and performance optimization, efficient and stable network applications can be built.

The above is the detailed explanation of Python network programming (common libraries, code cases, environment construction, etc.). For more information about Python network programming, please pay attention to my other related articles!