Python Central HubSign in

Python Programming / Python Networking

Sockets (TCP Client and Server)

Learn low-level networking with sockets by building a simple TCP server and client.

diagram the call sequence on both ends of a TCP connection mermaid
The two sides are not symmetric. A server binds a port, announces it is listening, and then blocks in accept until somebody arrives -- and accept returns a NEW socket for that one conversation, leaving the original still listening. The client only connects. Getting this order wrong is why a server refuses connections or only ever serves one.

What is a socket?

A socket is an endpoint for network communication.

For TCP:

  • server listens on (host, port)
  • client connects to (host, port)

Simple TCP server

Python
import socket
 
HOST = "127.0.0.1"
PORT = 5050
 
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print(f"Listening on {HOST}:{PORT}")
 
    conn, addr = s.accept()
    with conn:
        print("Connected by", addr)
        data = conn.recv(1024)
        print("received:", data.decode())
        conn.sendall(b"Hello client")

Simple TCP client

Python
import socket
 
HOST = "127.0.0.1"
PORT = 5050
 
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b"Hello server")
    data = s.recv(1024)
 
print("received:", data.decode())

Tips

  • Use 127.0.0.1 for local experiments.
  • Choose ports above 1024.
  • Add timeouts (s.settimeout(5)) to avoid hanging.
sketch TCP is a byte stream, not a sequence of messages p5.js
A client sent HELLO and WORLD as two separate calls. A receiver looping on recv(4) got HELL, then O, then WORL. Neither send arrived as a unit: the first was split across two reads and the second began in the middle of one. TCP guarantees the bytes arrive in order and intact, and guarantees nothing about where they are divided.

Check yourself

quizCheck yourself
  1. A client calls `sendall(b'HELLO')` then `sendall(b'WORLD')`. A receiver loops on `recv(4)`. What does it get?

    Show answer

    B — `[b'HELL', b'O', b'WORL']` — Measured. TCP delivers a byte stream — the send boundaries are not preserved, so one send can be split across reads and two sends can merge into one.

  2. `recv(1024)` returns 12 bytes. What does that mean?

    Show answer

    C — That is normal — it returns what is available — A short read is ordinary, not exceptional. Only a return of zero bytes means the peer closed the connection.

  3. Which of these is NOT a valid way to frame messages over TCP?

    Show answer

    D — Assuming each `recv` returns exactly one `sendall` — That assumption is precisely what the measurement disproves. It appears to work on localhost with small payloads, which is why it survives testing.

  4. What does `accept()` return on a listening server socket?

    Show answer

    B — A NEW socket for that one client, plus its address — The listening socket keeps listening; the new socket carries the conversation. Serving only one client is the usual symptom of reusing the listening socket by mistake.

🧪 Try It Yourself

Exercise 1 – HTTP GET with urllib

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Socket Connection

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Resolve a Hostname

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did