typestar

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

  1. SO_REUSEADDR lets the port rebind quickly.
  2. listen then accept waits for a client.
  3. Each connection is read and answered in a loop.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Sockets & networking, step 7 of 41 in Domain tools.

← Previous Next →