typestar

A TCP client in Python

Opening a socket and speaking raw HTTP to a server.

import socket

with socket.create_connection(("example.com", 80), timeout=5) as sock:
    request = (
        "GET / HTTP/1.1\r\n"
        "Host: example.com\r\n"
        "Connection: close\r\n\r\n"
    )
    sock.sendall(request.encode())
    chunks = []
    while chunk := sock.recv(4096):
        chunks.append(chunk)

response = b"".join(chunks)
status_line = response.split(b"\r\n", 1)[0]

How it works

  1. create_connection dials host and port.
  2. sendall writes the request bytes.
  3. recv loops until the server closes the stream.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
341
Tokens
100
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 1 of 4 in Sockets & networking, step 6 of 41 in Domain tools.

← Previous Next →

A TCP client in other languages