Run a real TCP server in a background thread, then use later Colab cells as clients. No fake network simulation.
Instead of keeping two notebook cells blocked by input(), the TCP server runs in a background thread. Other cells act as independent clients.
127.0.0.1:5000. Only the interaction style is adapted for a notebook.Observe the complete socket lifecycle without simulating it:
Copy this entire block into the first Colab cell and run it once.
import socket
import threading
HOST = "127.0.0.1"
PORT = 5000
chat_history = []
server_running = True
def handle_client(conn, addr):
try:
data = conn.recv(1024).decode("utf-8")
if not data:
return
chat_history.append(f"CLIENT {addr}: {data}")
print(f"[SERVER] received: {data}")
reply = f"ACK: {data}"
conn.sendall(reply.encode("utf-8"))
finally:
conn.close()
def server_loop():
global server_running
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((HOST, PORT))
server.listen()
server.settimeout(1)
print(f"[SERVER] listening on {HOST}:{PORT}")
while server_running:
try:
conn, addr = server.accept()
threading.Thread(
target=handle_client,
args=(conn, addr),
daemon=True
).start()
except socket.timeout:
pass
server_thread = threading.Thread(
target=server_loop,
daemon=True
)
server_thread.start()Run this in the second Colab cell. It defines a reusable client function but does not send anything yet.
import socket
def send_message(username, message):
payload = f"{username}: {message}"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
client.connect((HOST, PORT))
client.sendall(payload.encode("utf-8"))
reply = client.recv(1024).decode("utf-8")
print(f"[{username}] sent : {message}")
print(f"[{username}] received : {reply}")
return replysend_message("Alice", "Hello Server")
send_message("Bob", "Hello Alice")
send_message("Alice", "How are you?")def chat(username, messages):
for message in messages:
send_message(username, message)
chat("Alice", [
"Hello!",
"This is a real TCP socket.",
"Nice to meet you."
])
chat("Bob", [
"Hi Alice",
"I am Bob."
])print("=== SERVER CHAT HISTORY ===")
for item in chat_history:
print(item)chat_history proves that the background server processed the messages.server_running = False
server_thread.join(timeout=2)
print("[SERVER] stopped")