Back
+15 XP
Concept

TCP Sockets: Building a Simple Echo Server

A TCP server calls `.bind((host, port))`, `.listen(backlog)`, and `.accept()`. The server receives client bytes with `.recv()` and sends data back with `.sendall()` 📡.

python
import socket

# Standard echo server structure:
# server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# server.bind(('127.0.0.1', 8080))
# server.listen(5)
# conn, addr = server.accept()
# data = conn.recv(1024)
# conn.sendall(data)
print("TCP Server workflow: bind -> listen -> accept -> recv/sendall 📡")

# 72. TCP Sockets: Building a Simple Echo Server A TCP server calls `.bind((host, port))`, `.listen(backlog)`, and `.accept()`. The server receives client bytes with `.recv()` and sends data back with `.sendall()` 📡. ```python import socket # Standard echo server structure: # server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # server.bind(('127.0.0.1', 8080)) # server.listen(5) # conn, addr = server.accept() # data = conn.recv(1024) # conn.sendall(data) print("TCP Server workflow: bind -> listen -> accept -> recv/sendall 📡") ``` Use `conn.sendall(data)` instead of `conn.send(data)` because `send()` may only transmit a fraction of your bytes if network buffers are full! 📡 --- ### Question Why is `conn.sendall()` preferred over `conn.send()` when transmitting payloads over TCP? 🧠 - [ ] a. `sendall` continues sending until all bytes are transmitted or an error occurs 📡 - [ ] b. `sendall` automatically compresses data with gzip - [ ] c. `send` drops the TCP handshake connection randomly - [ ] d. `sendall` runs on a hidden GPU thread --- ### Challenge Write a function `format_echo(payload: bytes) -> bytes` that prepends `b'ECHO: '` to `payload`. Print `format_echo(b'ping')`. 🎯 <details> <summary>Solution</summary> ```python def format_echo(payload: bytes) -> bytes: return b"ECHO: " + payload print(format_echo(b"ping")) ``` </details>

Checkpoint

Why is `conn.sendall()` preferred over `conn.send()` when transmitting payloads over TCP? 🧠

Practice

Write a function `format_echo(payload: bytes) -> bytes` that prepends `b'ECHO: '` to `payload`. Print `format_echo(b'ping')`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks