TCP Programming
Python Socket Getting Started and Practical Combat
TCP is a connection-oriented and reliable transport layer protocol that supports most Internet applications such as HTTP, SSH, and email. in the Python standard librarysocketThe module provides a set of clear, cross-platform network programming interfaces. Starting from the basic concepts, this article will take you step by step to write a modern style TCP client and server, and at the same time understand the simple usage of UDP, optimization techniques in the production environment, as well as common problems and countermeasures.
1. Three core elements of Socket
To establish effective network communication, a socket needs to determine three elements at the same time:
- Target host identification: IPv4/IPv6 address or domain name (such as
www.example.com)。 - Port number: an integer between 1 and 65535, used to distinguish different services on the same host (such as HTTP default 80, HTTPS 443).
- Transmission Protocol:
SOCK_STREAM:TCP, a connection-oriented streaming protocol, ensures the orderly and reliable arrival of data.SOCK_DGRAM: UDP, a connectionless datagram protocol, does not guarantee reliability, but is more efficient in scenarios with high real-time requirements (such as live broadcasts and games).
2. TCP client programming
TCP establishes a connection through a "three-way handshake" and disconnects through a "four-way wave". Data transmission is like reading and writing files, it is an ordered byte stream.
2.1 The simplest HTTP client (traditional writing method, not recommended)
The following example demonstrates how to use the underlying socket to send a simple HTTP request. This way of writing requires manual callingclose(), it is easy to forget to release resources due to exceptions, and is not recommended for use in production now.
2.2 Recommended writing methods for modern Python
Utilize Context Manager(withstatement), Python will automatically close the socket at the end of the code block, and resources can be safely released regardless of whether an exception occurs.
3. TCP server programming
The core process of the server is: Create socket → Bind address and port → Start listening → Accept connection → Process request → Close connection.
3.1 Multi-threaded Echo Server (Basic Edition)
This version creates a new thread for each client to implement the "echo" function - return the received data as it is, and when encountering empty data orexitDisconnect on command.
3.2 Production-level simple optimized version
The basic version above does not limit the number of concurrent connections, nor does it set a timeout mechanism. Malicious connections may exhaust thread resources. Use belowconcurrent.futures.ThreadPoolExecutorTo improve:
Through the thread pool, we limit the number of requests processed at the same time to avoid resource exhaustion; the timeout setting prevents some connections from being unresponsive for a long time but occupying the thread.
4. Quick addition: UDP Socket
UDP is a connectionless, unreliable protocol that does not require a pre-established connection and has smaller latency, but may lose data or be out of order. It is very suitable for live video streaming, online games and other scenarios. The code below demonstrates a simple UDP server and client.
5. Best practices and pitfalls to avoid
Quick check to avoid pitfalls
General Advice
- Resource Management: Always use
withortry/finallyRelease socket resources. - Set Timeout: Passed
settimeout()Avoid long-term blocking of connections. - Production environment: Give priority to mature asynchronous frameworks (such as
asyncio、Tornado、FastAPIunderlying facilities). - use
sendall()substitutesend():sendall()Will continue to try to send until all data is written, andsend()It is possible to send only part of it and then return it.
6. Summary
This article demonstrates Python through concise, runnable codesocketCore usage of the module:
- TCP’s three-way handshake, four-way wave and the nature of streaming communication;
- From traditional manual
close()Writing style transitions to modernwithcontext manager; - From simple multi-threaded Echo server to thread pool + timeout production-level optimization;
- Example of connectionless communication via UDP;
- Pitfalls that are easily encountered during development and corresponding solutions.
If the business scenario is more complex, you can learn moreasyncioAsynchronous Socket, SSL/TLS encryption (ssl.create_default_context()) and other advanced themes to build higher-performance and more secure network applications.

