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
create_connectiondials host and port.sendallwrites the request bytes.recvloops until the server closes the stream.
Keywords and builtins used here
aswhilewith
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.
Step 1 of 4 in Sockets & networking, step 6 of 41 in Domain tools.