# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- TCP server: socket -> bind -> listen -> accept -> recv / send
import socket                       # Python's built-in networking module
 
HOST = '127.0.0.1'                    # listen on loopback for lab safety
PORT = 5000                         # the fixed port clients will connect to
 
# Create a TCP socket: AF_INET = IPv4, SOCK_STREAM = TCP.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    # Allow an immediate restart without "Address already in use".
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((HOST, PORT))       # attach the socket to IP + port
    server.listen()                 # start waiting for clients
    print('Server listening on port', PORT)
    # Block until a client connects; get a NEW socket for that client.
    conn, addr = server.accept()
    with conn:                      # closes the client socket at the end
        print('Connected by', addr)
        data = conn.recv(1024)      # read up to 1024 bytes (blocks)
        print('Received:', data.decode())     # bytes -> text
        conn.sendall(b'ACK ' + data)          # reply with bytes
