TCP sockets: a loopback echo server

TCP provides a reliable, ordered, byte-stream connection between two processes. A server creates a socket, binds it to an address and port, and listens. A client connects, and the server accepts the connection and gets a new socket for that client. Both sides then send and receive bytes until one of them closes.

Python
import socket
import threading

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 0))
server.listen(1)
port = server.getsockname()[1]


def serve():
    connection, _ = server.accept()
    with connection:
        data = connection.recv(1024)
        connection.sendall(data.upper())


thread = threading.Thread(target=serve)
thread.start()
with socket.create_connection(("127.0.0.1", port)) as client:
    client.sendall(b"hello tcp")
    reply = client.recv(1024)
thread.join()
server.close()
print(port > 0)
print(reply.decode())
Read the full lesson