Skip to content

Sockets (TCP Client and Server)

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

tcp_server.py
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")
tcp_server.py
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

tcp_client.py
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())
tcp_client.py
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.1127.0.0.1 for local experiments.
  • Choose ports above 1024.
  • Add timeouts (s.settimeout(5)s.settimeout(5)) to avoid hanging.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ HTTP GET with urllib

Exercise 2 โ€“ Socket Connection

Exercise 3 โ€“ Resolve a Hostname

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did