A TCP server in Python
Binding a socket and echoing back what clients send.
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 9000))
server.listen()
while True:
conn, addr = server.accept()
with conn:
data = conn.recv(1024)
if data == b"quit":
break
conn.sendall(b"echo: " + data)
server.close()
How it works
SO_REUSEADDRlets the port rebind quickly.listenthenacceptwaits for a client.- Each connection is read and answered in a loop.
Keywords and builtins used here
breakifwhilewith
The run, in numbers
- Lines
- 15
- Characters to type
- 331
- Tokens
- 95
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 54 seconds.
Step 2 of 4 in Sockets & networking, step 7 of 41 in Domain tools.