TCP 客户端与服务器套接字
通过使用 Python 构建基础 TCP 客户端和服务器应用,实现可靠的面向连接通信
TCP 客户端与服务器套接字 是 CoddyKit 上的免费 Linux Networking & TCP/IP for Developers 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Linux Networking & TCP/IP for Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Linux Networking & TCP/IP for Developers 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
TCP Sockets: Connection First
Welcome to building network applications with Python! This lesson focuses on TCP (Transmission Control Protocol) sockets, which are the backbone of reliable internet communication.
Unlike UDP, TCP is a connection-oriented protocol. This means a direct, stable link is established between two applications before any data is sent.
Why TCP is Reliable
TCP ensures your data arrives correctly and in order. It handles:
- Guaranteed Delivery: Data segments are retransmitted if lost.
- Ordered Data: Data arrives in the order it was sent.
- Error Checking: Data integrity is verified.
- Flow Control: Prevents a fast sender from overwhelming a slow receiver.
This makes TCP ideal for web browsing, email, and file transfers.
TCP Server: The Listener
A TCP server's role is to listen for incoming connections from clients. Here's the typical workflow for a server:
- Create a socket.
- Bind the socket to an IP address and port.
- Listen for client connections.
- Accept an incoming connection.
- Communicate (send/receive data).
- Close the sockets.
Creating a Python TCP Socket
In Python, we use the built-in socket module. To create a TCP socket, we specify socket.AF_INET for IPv4 addressing and socket.SOCK_STREAM for TCP.
Try running this basic example:
import socket
def main():
# Create a TCP/IP socket
# AF_INET for IPv4, SOCK_STREAM for TCP
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("TCP socket created successfully!")
tcp_socket.close()
print("Socket closed.")
if __name__ == "__main__":
main()Server: Bind to Address & Port
After creating the socket, the server needs to bind it to a specific IP address and port number. This tells the operating system where the server will listen for connections.
.bind((HOST, PORT)) associates the socket. .listen(backlog) prepares it to accept connections, with backlog being the max queued connections.
import socket
def main():
HOST = '127.0.0.1' # Localhost
PORT = 65432 # Port to listen on (non-privileged)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server_socket.bind((HOST, PORT))
server_socket.listen(1) # Allow 1 pending connection
print(f"Server listening on {HOST}:{PORT}")
except Exception as e:
print(f"Error binding or listening: {e}")
finally:
server_socket.close()
print("Server socket closed.")
if __name__ == "__main__":
main()Server: Accepting a Client
The .accept() method is crucial for a server. It blocks execution until a client tries to connect. When a connection is made, it returns two values:
- A new socket object (
conn) for communicating with that specific client. - The client's address (
addr), a(host, port)tuple.
import socket
def main():
HOST = '127.0.0.1'
PORT = 65432
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(1)
print(f"Server waiting for connection on {HOST}:{PORT}...")
# This will block until a client connects
conn, addr = server_socket.accept()
with conn: # Use 'with' for auto-closing the client socket
print(f"Connected by client from {addr}")
# In a real app, send/recv would happen here
conn.sendall(b"Hello from server!") # Send some bytes
print("Sent greeting to client.")
server_socket.close()
print("Server socket closed.")
if __name__ == "__main__":
main()TCP Client: Initiating Connection
A TCP client's role is to initiate a connection to a server. Here's its typical workflow:
- Create a socket.
- Connect to the server's IP address and port.
- Communicate (send/receive data).
- Close the socket.
Client: Connecting to Server
The client uses the .connect((HOST, PORT)) method to establish a connection with the server. If successful, a virtual circuit is created. If the server isn't listening, you'll get a ConnectionRefusedError.
Run this. If no server is running, it will show an error:
import socket
def main():
HOST = '127.0.0.1' # Server's IP address
PORT = 65432 # Server's port
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print(f"Attempting to connect to server at {HOST}:{PORT}...")
client_socket.connect((HOST, PORT))
print("Successfully connected to the server!")
except ConnectionRefusedError:
print("Connection refused. Is the server running?")
except Exception as e:
print(f"Client connection error: {e}")
finally:
client_socket.close()
print("Client socket closed.")
if __name__ == "__main__":
main()Sending & Receiving Data
Once connected, both client and server can send and receive data. Remember that network data is transmitted as bytes, so you'll often need to .encode() strings before sending and .decode() received bytes back into strings.
.sendall(data): Sends all data reliably..recv(buffer_size): Receives up tobuffer_sizebytes.
import socket
def main():
HOST = '127.0.0.1'
PORT = 65432
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client_socket.connect((HOST, PORT))
message = "Hello from the client!"
client_socket.sendall(message.encode('utf-8'))
print(f"Client sent: '{message}'")
data = client_socket.recv(1024) # Receive up to 1024 bytes
if data:
print(f"Client received: '{data.decode('utf-8')}'")
else:
print("Client received no data (server might have closed).")
except ConnectionRefusedError:
print("Connection refused. Please run the server example first!")
except Exception as e:
print(f"Client communication error: {e}")
finally:
client_socket.close()
print("Client socket closed.")
if __name__ == "__main__":
main()TCP Communication Flow
Consider the typical steps for a Python TCP server to establish a connection and an echo client to communicate.
Recap: TCP Client-Server Sockets
Great job! You've learned the fundamentals of TCP client-server communication in Python:
- TCP provides reliable, connection-oriented communication.
- Servers bind to an address, listen for connections, and accept clients.
- Clients connect to a server's address.
- Both use
.sendall()to send and.recv()to receive bytes.
These concepts are crucial for building robust networked applications!
常见问题解答
「TCP 客户端与服务器套接字」课时是免费的吗?
是的 — 「TCP 客户端与服务器套接字」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Linux Networking & TCP/IP for Developers 课程的其余内容,请升级到 CoddyKit PRO。 Linux Networking & TCP/IP for Developers 课程共包含 4 节课。
「TCP 客户端与服务器套接字」这节课中我会学到什么?
通过使用 Python 构建基础 TCP 客户端和服务器应用,实现可靠的面向连接通信 你通过在浏览器中直接运行的动手代码来练习 Linux Networking & TCP/IP for Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Linux Networking & TCP/IP for Developers 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Linux Networking & TCP/IP for Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「TCP 客户端与服务器套接字」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Linux Networking & TCP/IP for Developers 课中编写并运行代码吗?
能。每节 Linux Networking & TCP/IP for Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Socket API 入门
- TCP 客户端与服务器套接字
- UDP 客户端与服务器套接字
- 非阻塞套接字与 select()