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.

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.10or0.0.1for the local machine). - Port Number: A number that identifies a specific application or service on that machine (e.g., port
80for HTTP, port443for HTTPS). Ports range from 0 to 65535.
Key Socket Types
The socket module supports different types of sockets, but the most common are:

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:
- Create a socket.
- Bind the socket to an IP address and port.
- Listen for incoming connections.
- Accept a connection when one arrives.
- Receive data from the client.
- Send a response back.
- 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:
- Create a socket.
- Connect to the server's IP address and port.
- Send data to the server.
- Receive a response from the server.
- 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:
-
Save the two files as
server.pyandclient.py.
(图片来源网络,侵删) -
Open two terminal windows.
-
In the first terminal, run the server:
python server.py
You will see:
Server is starting...andServer is listening on 0.0.0.0:65432. The program will now wait for a connection. -
In the second terminal, run the client:
python client.py
The client will connect, send a message, and print the server's response.
-
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...exceptblocks to handle network errors likeConnectionRefusedError,TimeoutError, orOSError. - Concurrency: The
s.accept()ands.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 likeasyncio. - 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
socketmodule does not provide encryption. For secure communication (HTTPS, etc.), you should use thesslmodule to wrap your sockets.
