Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsiTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
To create a simple TCP server in Python, make a stream socket, bind it to an address and port, call listen(), then use accept() to get a separate socket for each client connection. The example below binds to IPv4 loopback, so it is reachable only from the same computer, and echoes bytes back to clients one at a time.
How do I create a simple TCP server in Python?
Python’s built-in socket module provides the low-level operations needed to accept TCP connections. This learning example uses 127.0.0.1 for a local test, repeats accept() for successive clients, and closes sockets with context managers.
import socket
HOST = "127.0.0.1" # IPv4 loopback: local connections only
PORT = 50007
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.bind((HOST, PORT))
server.listen()
print(f"Listening on {HOST}:{PORT}")
while True:
conn, address = server.accept()
with conn:
print("Connected by", address)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Save the file as server.py and run it with Python. The program waits for a client, prints its address, and sends back any bytes it receives. It continues accepting later connections after each client disconnects. This is an illustrative adaptation of the Python Software Foundation’s official socket example, not a production-ready service.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11What each socket call does
socket.socket(socket.AF_INET, socket.SOCK_STREAM)creates an IPv4 stream socket;SOCK_STREAMis the socket type used for TCP.bind((HOST, PORT))assigns the listening socket a local address and port.listen()marks it as ready to accept incoming connections. The operating system manages a queue of connection requests that have not yet been accepted; omitting a backlog lets the system choose a default rather than guaranteeing a particular capacity.accept()waits for a connection and returns a new socket plus the peer address.recv(1024)reads bytes from that connection. If it returns an empty byte string, the peer has closed its sending side.sendall(data)sends the received bytes back, continuing until all of that byte string has been sent or an error occurs.
The Python Software Foundation describes the server sequence as socket(), bind(), listen(), and accept(), with accept() repeated to service more than one client. A client instead connects with connect(). See the socket reference.
#1 Best Overall
- Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM)
- Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
- CanaKit Turbine Black Case for the Raspberry Pi 5
- CanaKit Low Noise Bearing System Fan
- Mega Heat Sink - Black Anodized
Why does accept() return another socket?
The original server socket remains in listening mode: it waits for new connections. Each call to accept() returns a distinct conn socket for communication with one connected client, along with that client’s address. Read and write client data through conn, not through server. Keeping these roles separate lets the server continue listening for connections after it finishes handling the current one.
How can I test a Python socket server locally?
Run the server in one terminal, then run this small client in another terminal on the same computer. It connects to the same loopback address and port, sends bytes, and prints the echoed response.
Rank #2
- Includes Raspberry Pi 5 16GB with 2.4Ghz 64-bit quad-core CPU (16GB RAM)
- Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
- CanaKit Turbine Black Case for the Raspberry Pi 5
- CanaKit Low Noise Bearing System Fan
- Mega Heat Sink - Black Anodized
import socket
HOST = "127.0.0.1"
PORT = 50007
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
client.connect((HOST, PORT))
client.sendall(b"Hello, server")
print(client.recv(1024))
The expected output is b'Hello, server'. The server prints the client’s address when the connection is accepted. If the client reports that the connection was refused, check that the server is running, that both programs use the same port and address, and that no other process has taken that port.
What does the server’s bind address change?
127.0.0.1 is the IPv4 loopback address. Binding to it limits connections to the same machine, which is the safer choice for a beginner’s local exercise. The empty host string, "", means all available interfaces in the Python documentation’s example. That can make a service reachable through the machine’s network addresses by other devices, subject to firewall and network configuration. Use it only when you intend to allow that reachability.
Rank #3
- CanaKit Raspberry Pi 5 Essentials Starter Kit
The example explicitly selects IPv4 with AF_INET. IPv6 and dual-stack behavior depends on the address family and platform. Python’s socket reference demonstrates resolving addresses with getaddrinfo() and warns that choosing only the first available address family may leave the server unable to accept traffic on another family. It also documents socket.create_server(), available since Python 3.8, with a platform-dependent dualstack_ipv6 option; neither guarantees identical behavior across systems.
How do I make a Python server handle more than one client?
The loop in the example accepts successive clients, but handles them serially: while it is reading from one client, it does not accept another. A client that stays connected without sending data can therefore keep later clients waiting. Concurrent client handling requires a different design, such as using threads or asynchronous I/O; the minimal example does not implement either.
Rank #4
- All-in-One Complete Kit: This SANOOV RPi 5 bundle comes with Raspberry Pi 5 4GB RAM single board, active cooler, durable ABS case and screwdriver. No extra parts needed, ready to use right out of the box for beginners and hobbyists
- Powerful Single Board Computer: Equipped with 4GB RAM and high-performance processor, delivers fast running speed for 4K playback, AI projects, programming and daily computing tasks. SANOOV for raspberry pi 5 4GB is equipped with broadcom 64 quad-core Arm Cortex A76 processor with gigabit ethernet and upgraded with IEEE 802.11ac Wi-Fi, Bluetooth 5.0 dual-band 2.4Ghz and 5Ghz and Power Over Ethernet (POE). Upgrading delivers 2-3 x speed vs Pi 4, redefining the experience
- Efficient Active Cooler: Effectively lowers operating temperature and prevents performance throttling. Runs quietly even under long-time heavy load, ensures stable operation all day long. SANOOV RPi 5 4GB kit offer an active cooler, which combines an aluminium heatsink with a high-performance PWM fan. Active cooler is fully compatible with the Pi OS, which can effectively reduce the temperature of RPi5 and ensure its good performance during long-term high load operation
- Sturdy ABS Protective Case: Well-fitted for Raspberry Pi 5 board, can be secured with 4 screws to effectively protect the Pi 5 motherboard from damage, reserves full access to all ports and buttons. SANOOV uses ABS material to produce the case, which has a softer texture and feel. Meanwhile, SANOOV case adopts a layered design for easy disassembly and installation. (Tip: The Case cannot install M.2 HAT Add on Board and Solid State Drive!)
- Wide Application & Full Compatibility: Seamlessly compatible with official OS and mainstream peripheral accessories for Raspberry Pi 5. Whether you are a beginner, student, electronics hobbyist or professional developer, this all-in-one kit meets your diverse needs. It excels in IoT projects, robotics design, retro gaming devices, home media servers and other DIY creations. Backed by a large global community, you can easily find guides, technical support and shared projects online
The listen backlog is not a substitute for concurrent handling. It concerns connection requests waiting to be accepted, and the operating system may choose the default when no backlog is specified. It is not a promise that the server can process a fixed number of clients simultaneously.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Why is recv(1024) not a complete message?
TCP provides an ordered byte stream, not application-level message boundaries. recv(1024) means “read up to 1024 bytes”; it may return fewer bytes, and a single send by the client is not guaranteed to correspond to one receive on the server. The echo example sends back each chunk it gets, which is enough to demonstrate the socket lifecycle but does not define a general message protocol.
Best Value
- 【What you Get】You will get 1*Pi 5 8GB Single Board,1*RasTech Case,1*Active Cooler,1*Screwdriver,1*Installation instructions,12-month free warranty, lifetime service, 24-hour prompt and friendly response.
- 【More Connectors】There are two USB 3.0 ports(5Gbps simultaneously) and two USB 2.0 ports, which triple total bandwidth ,support any combination of up to two cameras or displays. Peak SD card performance is doubled through support for the SDR104 high-speed mode. It provides a smooth desktop experience for you. Offer Gigabit Ethernet and a PCIe interface, along with dual-band Wi-Fi and Bluetooth 5.0/BLE wireless capability. The RasTech Pi 5 Kit use the new 27W 5.1V 5A USB-C power connector.
- 【 Support Dual 4Kp60 Display 】Each of the two microHDMI sockets can control a 4K display at 60 Hertz, now support HDR, offering super HD video for media streaming projects. RPi 5 is the first RPi model that comes with a PCI Express port (PCIe 2.0 x1 with 500 MB/s) to attach SSDs (requires separate M.2 HAT).
- 【 Excellent Chips And Applications】Pi 5 is a full-size Pi computer using silicon built in-house at Pi. The RP1 “southbridge” provides the bulk of the I/O capabilities for Pi 5. Pi 5 is more friendly and convenient in the development of Internet of Things, Web development, machine identification, automatic control and other electronic equipment applications and network.
- 【 Faster CPU, Better GPU 】 Pi 5 features a Broadcom BCM2712 64-bit quad-core Arm Cortex-A76 processor running at 2.4GHz, it delivers a 2–3× increase in CPU performance relative to RaspberryPi 4. The 800MHz VideoCore VII GPU is compatible to OpenGL ES 3.1 and Vulkan 1.2, substantial uplift in graphics performance. Pi 5 Offers lightning-fast CPU speed, a PCI Express interface, a Real Time Clock (RTC) and a power button and runs significantly cooler than Pi 4.
For an application protocol, choose a framing rule, such as a fixed-size message, a delimiter, or a length prefix, and implement both sending and receiving around it. Also define how text is encoded and decoded rather than assuming that arbitrary received bytes are a complete text message. The Python Software Foundation’s Socket Programming HOWTO explains stream behavior and the need for applications to handle message boundaries.
When is this example appropriate?
- Use a raw socket example to learn TCP’s connection lifecycle or to build a deliberately custom byte-stream protocol.
- For an HTTP application, start with a higher-level server framework or library rather than treating this echo loop as a web server.
- Before exposing a service beyond loopback, design its protocol and error handling, decide how it will manage multiple clients, and account for the host’s network and firewall configuration.
The context managers close the listening socket when the outer block exits and each accepted connection when its inner block exits. A more robust program should also handle expected OSError conditions, such as a port that cannot be bound; this small teaching example intentionally keeps error handling minimal.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

