杰瑞科技汇

Python import socket 如何实现网络通信?

Of course! The import socket statement in Python is your gateway to the world of network programming. It gives you access to the socket module, which provides a low-level networking interface based on the BSD sockets API.

Python import socket 如何实现网络通信?-图1
(图片来源网络,侵删)

This is the fundamental building block for creating both clients and servers that communicate over a network (like the internet or a local network).


What is a Socket?

Think of a socket as an endpoint for sending or receiving data across a computer network. To communicate, you need two sockets: one on the client side and one on the server side.

A socket is uniquely identified by an IP address and a port number.

  • IP Address: The unique address of a machine on the network (e.g., 168.1.10 or 0.0.1 for the local machine).
  • Port Number: A number that identifies a specific application or service on that machine (e.g., port 80 for HTTP, port 443 for HTTPS). Ports range from 0 to 65535.

Key Socket Types

The socket module supports different types of sockets, but the most common are:

Python import socket 如何实现网络通信?-图2
(图片来源网络,侵删)
  • socket.AF_INET: This is the address family for IPv4 (e.g., 168.1.1).
  • socket.AF_INET6: This is the address family for IPv6.
  • socket.SOCK_STREAM: This is the TCP (Transmission Control Protocol) socket type. It's a connection-oriented protocol, meaning it provides a reliable, ordered, and error-checked stream of data. It's like making a phone call.
  • socket.SOCK_DGRAM: This is the UDP (User Datagram Protocol) socket type. It's a connectionless protocol, meaning it sends packets of data without establishing a persistent connection. It's like sending a postcard—fast, but not guaranteed to arrive or be in order.

A Simple "Hello, World!" Example: A TCP Server and Client

This is the classic example to understand the basics. We'll create a simple server that listens for a connection and a client that connects to it.

Part A: The Server (server.py)

The server's job is to:

  1. Create a socket.
  2. Bind the socket to an IP address and port.
  3. Listen for incoming connections.
  4. Accept a connection when one arrives.
  5. Receive data from the client.
  6. Send a response back.
  7. Close the connection.
# server.py
import socket
# Use '0.0.0.0' to listen on all available network interfaces
# Use '127.0.0.1' to listen only on the local machine (localhost)
HOST = '0.0.0.0'  
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)
print("Server is starting...")
# 1. Create a socket object
#    AF_INET for IPv4, SOCK_STREAM for TCP
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    # 2. Bind the socket to a specific address and port
    s.bind((HOST, PORT))
    # 3. Listen for incoming connections (the argument is the backlog of connections)
    s.listen()
    print(f"Server is listening on {HOST}:{PORT}")
    # 4. Accept a connection. This is a blocking call.
    #    It returns a new socket object to communicate with the client,
    #    and the address of the client.
    conn, addr = s.accept()
    with conn:
        print(f"Connected by {addr}")
        while True:
            # 5. Receive data from the client (up to 1024 bytes)
            data = conn.recv(1024)
            if not data:
                # If recv() returns an empty object, the client has closed the connection
                break
            print(f"Received from client: {data.decode('utf-8')}")
            # 6. Send a response back to the client
            response = "Hello, Client! I've received your message."
            conn.sendall(response.encode('utf-8'))
    print("Client disconnected.")
print("Server has shut down.")

Part B: The Client (client.py)

The client's job is to:

  1. Create a socket.
  2. Connect to the server's IP address and port.
  3. Send data to the server.
  4. Receive a response from the server.
  5. Close the connection.
# client.py
import socket
HOST = '127.0.0.1'  # The server's hostname or IP address (localhost for testing)
PORT = 65432        # The port used by the server
print("Client is starting...")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    # 1. Connect to the server
    s.connect((HOST, PORT))
    print(f"Connected to server at {HOST}:{PORT}")
    # 2. Send data to the server (must be in bytes)
    message = "Hello, Server!"
    s.sendall(message.encode('utf-8'))
    print(f"Sent to server: {message}")
    # 3. Receive data from the server (up to 1024 bytes)
    data = s.recv(1024)
print(f"Received from server: {data.decode('utf-8')}")

How to Run It:

  1. Save the two files as server.py and client.py.

    Python import socket 如何实现网络通信?-图3
    (图片来源网络,侵删)
  2. Open two terminal windows.

  3. In the first terminal, run the server:

    python server.py

    You will see: Server is starting... and Server is listening on 0.0.0.0:65432. The program will now wait for a connection.

  4. In the second terminal, run the client:

    python client.py

    The client will connect, send a message, and print the server's response.

  5. Back in the first terminal, you will see the server acknowledge the connection and the message it received.


Common Socket Methods

Here's a quick reference for the most important methods:

Method Description
s = socket.socket(family, type) Creates a new socket object.
s.bind((host, port)) Binds the socket to a network address and port.
s.listen(backlog) Puts the socket into listening mode. backlog is the number of connections to queue.
conn, addr = s.accept() Accepts a new connection. Returns a new socket conn for communication and the client's addr.
s.connect((host, port)) Connects the socket to a remote address.
s.sendall(data) Sends all data (bytes) to the connected socket. It continues to send until all data is sent or an error occurs.
data = s.recv(bufsize) Receives up to bufsize bytes of data from the socket. Returns an empty bytes object if the connection is closed.
s.close() Closes the socket.
s.with s: Using a with statement is highly recommended as it automatically calls s.close() when the block is exited, even if errors occur.

Important Considerations

  • Error Handling: Real-world code needs robust try...except blocks to handle network errors like ConnectionRefusedError, TimeoutError, or OSError.
  • Concurrency: The s.accept() and s.recv() calls are blocking. This means the server will pause and wait. To handle multiple clients, you need to use threads, multiprocessing, or an asynchronous framework like asyncio.
  • Data Encoding: Network sockets send and receive raw bytes. You must encode your strings (e.g., using .encode('utf-8')) before sending and decode them (e.g., using .decode('utf-8')) after receiving.
  • Security: The basic socket module does not provide encryption. For secure communication (HTTPS, etc.), you should use the ssl module to wrap your sockets.
分享:
扫描分享到社交APP
上一篇
下一篇