Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Connected Networks StudioNetworking and CommunicationExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 37 · TCP echo server and client
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P37
Networking and Communication

Lab 37 · TCP echo server and client

Ask Dr. Mohammad · P37 →

Sockets on 127.0.0.1 are identical on WSL.

Open TCP packet analyzer →

Design experiment & verify evidence →
P37 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP37 · TCP echo server and client
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: IoT Programming and Applications — same laboratory, notebook and completion record.

P37 · Academic orientation

Scope and objectives

Scope of the experiment

Reassemble newline-delimited application messages from arbitrary TCP read chunks.

The focus of this experiment is to trace TCP connection, stream data and echo behavior. Students then distinguish application message boundaries from TCP byte-stream reads, and verify received bytes and diagnose binding or connection failures. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Trace TCP connection, stream data and echo behavior.
  • Distinguish application message boundaries from TCP byte-stream reads.
  • Verify received bytes and diagnose binding or connection failures.
  • Identify the configured inputs (Bytes per simulated recv(); Receiver strategy) and record the corresponding observed outputs with units where applicable.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can trace TCP connection, stream data and echo behavior, distinguish application message boundaries from TCP byte-stream reads, and verify received bytes and diagnose binding or connection failures.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing verify received bytes and diagnose binding or connection failures. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 38 · UDP datagrams and broadcast.

Environment and experimental methodology

The browser instrument and the specified local software or network environment. Use the experiment’s documented topology and distinguish modeled values from actual packet observations.

Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.

P37 / PREPARE

Before starting

Follow the setup guide and use the named terminal or editor. A browser model is not a real GPIO measurement or a running service.

Ubuntu WSL setup →
Before you run / verification gate

Run server first on loopback. The LAN exercise is optional, requires an instructor-approved network and a matching actual interface address; do not expose the server publicly. Stop your own server before repeating.

CONCEPTS / ACTIVE RECALL

Understand the experiment

TCP stream framing

Application message boundaries are reconstructed across recv calls
Application message boundaries are reconstructed across recv calls

Scientific architecture · TCP echo stream and message framing

TCP byte-stream echo — Client; TCP server; Application parser; Connect / 0>1; Send bytes / 0>1; Receive chunks, frame / 1>2; Echo framed bytes / 1>0
Scientific concept map: TCP client — Connect and send bytes; Transport stream — No message boundaries; Server buffer — Accumulate until framing; Echo server — Return message; Client — Compare received bytes.

Scientific foundations and analytical reasoning

TCP delivers an ordered byte stream without application-message boundaries. A receiver must accumulate bytes until a framing rule is satisfied.

Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.

Scientific theory · TCP stream and application framing

TCP establishes a connection and delivers bytes in order with loss recovery. It does not retain the sender's write boundaries: one read can contain part of a record or several records. Application framing such as a delimiter or length field is needed when multiple records share a connection.

Worked example and engineering interpretation

If a sender writes 'ABC' and 'DEF', a receiver may read 'AB' then 'CDEF'. The concatenated byte stream is ABCDEF. An echo protocol should compare complete framed bytes rather than assume one recv call equals one send call. Use loopback or an approved server.

Engineering principles · additional worked teaching example

TCP is an ordered byte stream, not a message protocol. Chunks may split or join logical records. Given 'A\nB\nC\n' read in 4-byte chunks, first chunk contains two records and second one; the delimiter parser handles both.

From theory to experiment

Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.

How to investigate Lab 37 · TCP echo server and client

Establish a TCP echo exchange and verify its acknowledgment.

Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.

Experiment-specific guided practice

Objective: Establish a TCP echo exchange and verify its acknowledgment.

  1. Run the buffered receiver with 3-byte reads. Inspect each partial buffer and emitted complete line.
  2. Select one recv = one message and compare parsed message count and correctness.
  3. Restore buffered parsing; set recv size to 20. Confirm two messages can arrive in one read.
  4. Run the corresponding local TCP client/server source and verify stream framing independently.

Reference check:

Model boundary:

Independent task and submission evidence

2. Select one recv = one message and compare parsed message count and correctness. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.

Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.

Worked engineering reasoning and boundary conditions

Engineering reference configuration: Bytes per simulated recv() = 3; Receiver strategy = buffered. In the classroom model, recv calls = 4; Parsed messages = 2; Correct messages = 2. The chunk segmentation is a controlled fixture, not a network timing prediction. A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.

Concept animation · message sequence

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

Lab 37 · TCP echo server and client: message sequenceClientTCP streamParser"hel" →"lo\n" → hello"wor" →"ld\n" → world

Step 1 of 4 · "hel" →

"hel" →

1. TCP stream → Parser
"hel" →

Teaching example only; inspect live calculations or real practical evidence separately.

Recall the concept before revealing its explanation.

0 / 3 revealed
P37 · 01 / 08What is TCP?Reveal explanation
Engineering explanation

A reliable ordered byte stream between two connected endpoints.

P37 · 02 / 08What proves an echo?Reveal explanation
Engineering explanation

The server prepends ACK and a space to the received bytes. The client should print Server replied: ACK temp=24.5. This small-message example is not a general TCP framing protocol.

P37 · 03 / 08What server/client conditions must be established before checking the TCP echo?Reveal explanation
Engineering explanation

Run server first on loopback. The LAN exercise is optional, requires an instructor-approved network and a matching actual interface address; do not expose the server publicly. Stop your own server before repeating.

P37 · 04 / 08Why can TCP data arrive in multiple reads?Reveal explanation
Engineering reasoning

TCP is a byte stream, not a record protocol; applications must handle partial reads and define framing.

P37 · 05 / 08Why bind the teaching echo service to loopback?Reveal explanation
Engineering reasoning

It permits a local client/server check without exposing an unnecessary network listener to other hosts.

P37 · 06 / 08A TCP echo client receives a reply. Select every technically valid statement. A. TCP is a reliable ordered byte stream within a connection. B. Application framing must distinguish logical messages. C. Each send call necessarily maps to exactly one recv call. D. TCP acknowledgments prove the application processed every record.Reveal explanation
Applied scenario

Correct: A. TCP is a reliable ordered byte stream within a connection.; B. Application framing must distinguish logical messages.

P37 · 07 / 08In TCP echo server and client, which command or code executes Connections?Reveal explanation
Implementation recall

ss -ltn | grep ":5000"

P37 · 08 / 08For TCP echo server and client, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Terminal A starts echo_server.py and stays open; B runs echo_client.py. Expected Server replied: ACK temp=24.5. For listener inspection use ss -ltn, not only ss -tn after the short connection closes. Stop A with Ctrl+C. This is loopback application framing, not LAN or physical transmission.

Execution boundary · Real on WSL. Browser simulation below is a teaching model, not execution of Python or firmware. The real commands run in VS Code/WSL; Wokwi is used for Arduino/ESP32 where indicated.

Network performance laboratory

Investigate seeded abstract queueing, traffic scalability and QoS trade-offs separately from actual service deployment.

Open Network Lab →
Independent conceptual protocol trace

Animated Lab 37 · TCP echo server and client

Use the scenario selector to explore reference, failure and recovery. The animation is explanatory, separate from the actual terminal exercise. Animation timing is for learning, not measured protocol latency.

Recent trace events
    Shared research workbenches · network designer & advanced studies
    Concurrent-device simulation & Monte Carlo research
    Distributed digital twin · topology, protocol & battery research
    Loading experiment-specific apparatus…
    Previous model / additional reference tools
    Simulation task

    Establish a TCP echo exchange and verify its acknowledgment.

    Explore the model using its own controls. Record a prediction before changing a condition. Compare the reference with a changed condition, then use the Experiment tab for the procedure, acceptance criteria and notebook. Model outputs and physical observations must remain separate.

    Interactive engineering workbenchP37 · Existing model
    01 / Explore

    Interactive lab simulation

    Browser model
    P37 · Model-linked instrumentation

    Visual observation lens

    Back to controls ↑

    Original virtual instrument; model signals and execution trace.

    Loading instrument…

    Awaiting model display.

    Experimental instrumentation · A/B

    Compare two model conditions

    Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.

    Open simulation view
    Baseline A
    Not captured
    Comparison B
    Not captured

    Capture a baseline to begin.

    Evidence portfolio →
    V19.0 · Contextual AI workspace

    Ask your engineering assistants

    P37 · current context

    Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.

    Dr. Mohammad · offline
    Dr. Mohammad

    Offline curriculum-grounded assistance.

    Open local tutor
    Lab 37 · TCP echo server and client

    Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.

    Prepare a contextual AI prompt

    0 characters

    Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.

    Prepare → review → copy & open your selected provider → paste and submit there.

    Run & verify — acceptance checklist

    Build verification: Actual loopback TCP echo exchange passed.

    Terminal A starts echo_server.py and stays open; B runs echo_client.py. Expected Server replied: ACK temp=24.5. For listener inspection use ss -ltn, not only ss -tn after the short connection closes. Stop A with Ctrl+C. This is loopback application framing, not LAN or physical transmission.

    Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

    Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

    Independent theoretical exercises

    Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.

    01 · Predict and derive using the given inputs

    Split the byte string A\nBC\n into chunks of at most 3 bytes. Reassemble by newline and count messages.

    02 · Compare or justify using evidence

    Explain why treating each recv as a whole message fails even on a reliable stream; predict how an incomplete final frame should be handled.

    03 · Code tracing

    Code tracing · Independent work

    Chunks are 'AB', 'C\nD', 'E\nF'. List complete messages and buffered remainder. What happens if EOF occurs now?

    Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.

    Expanded independent theoretical exercise bank

    Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.

    Intermediate · Explain a changed-input result

    Independent theoretical exercise · P37-01

    Use the reference configuration (Bytes per simulated recv() = 3; Receiver strategy = buffered), but change Bytes per simulated recv() = 5. The model reports recv calls = 3. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

    Intermediate · Quantitative comparison

    Independent theoretical exercise · P37-02

    Two model observations of recv calls are 4 (reference) and 3 (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

    Intermediate · Interpret a technical trace

    Independent theoretical exercise · P37-03

    For Receiver strategy = one recv = one message, the model supplies this excerpt from TCP receive trace: Offset · Received bytes · Emitted lines · Remaining buffer 0 · "hel" · hel · "" 3 · "lo\n" · lo · "" 6 · "wor" · wor · "" 9 · "ld\n" · ld · "" Count rows whose Received bytes value is exactly “"hel"”, and identify the displayed row numbers. Explain what the count describes.

    Advanced · Reverse reasoning

    Independent theoretical exercise · P37-04

    An observation is Parsed messages = 4. Candidate A uses Bytes per simulated recv() = 3; Receiver strategy = buffered. Candidate B changes the listed settings (Receiver strategy = one recv = one message) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

    Advanced · Diagnose a reported mismatch

    Independent theoretical exercise · P37-05

    A student configures Bytes per simulated recv() = 20 while preserving all other reference settings, but copies the reference report of recv calls = 4. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

    Challenging · Design a controlled verification

    Independent theoretical exercise · P37-06

    Design a controlled comparison for Lab 37 · TCP echo server and client using reference Bytes per simulated recv() = 3; Receiver strategy = buffered and test Bytes per simulated recv() = 5. Specify the changed setting(s), measured metric recv calls, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

    Step-by-step experimental procedure

    Reassemble newline-delimited application messages from arbitrary TCP read chunks.

    1 · Reference workbench configuration

    Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.

    Bytes per simulated recv()3
    Receiver strategybuffered

    2 · Perform the investigation in order

    1. Run the buffered receiver with 3-byte reads. Inspect each partial buffer and emitted complete line.
    2. Select one recv = one message and compare parsed message count and correctness.
    3. Restore buffered parsing; set recv size to 20. Confirm two messages can arrive in one read.
    4. Run the corresponding local TCP client/server source and verify stream framing independently.

    3 · Compare controlled trials

    TrialIndependent changeExpected checkObservation
    Buffered parsingUse reference inputs aboveCorrect messages: 2Record actual result
    Small chunks naiveReceiver strategy = one recv = one messageCorrect messages: 0Record actual result
    Single coalesced recvBytes per simulated recv() = 20Correct messages: 2Record actual result

    4 · Analyze and report

    TCP preserves byte order, not application message boundaries.

    Required evidence: Record the named metrics and trace for the reference and changed cases, then attach the corresponding practical command output or device evidence if available.

    Model boundary: A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

    Controlled investigation · reproducible evidence

    Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.

    TrialIndependent changeDependent observation
    Buffered parsingUse reference inputs aboveRecord actual outcome and units
    Small chunks naiveReceiver strategy = one recv = one messageRecord actual outcome and units
    Single coalesced recvBytes per simulated recv() = 20Record actual outcome and units

    Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.

    Loading laboratory-specific procedure…

    Python / Google Colab notebook

    Actual local loopback exchange with bounded sockets; no external network. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

    Download NotebookOpen Google ColabAll Python notebooks

    Independent implementation sequence

    1. Terminal 1: server first
    2. Terminal 2: client
    3. Connections
    4. LAN version (lan_tcp_server.py)
    5. If “Address already in use”
    6. Stop background processes
    02 / Implement

    Step-by-step instructions

    Before you run / verification gate

    Run server first on loopback. The LAN exercise is optional, requires an instructor-approved network and a matching actual interface address; do not expose the server publicly. Stop your own server before repeating.

    Complete one-time setup first. Copy one command block at a time into the indicated environment. Do not copy prompt characters. Open new terminals where named; variables are terminal-specific. Ctrl+C stops a running foreground command.

    01

    Terminal 1: server first

    WSL · Bash
    source ~/psut-wsl/activate.sh
    cd ~/psut-wsl/labs/python/lab37 && python echo_server.py
    ✓ Expected: Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected. If successful, Server listening on port 5000
    Expected result for each action (2)
    1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
    2. cd ~/psut-wsl/labs/python/lab37 && python echo_server.pyNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected. If successful, Server listening on port 5000
    Checkpoint Server listening on port 5000
    02

    Terminal 2: client

    WSL · Bash
    source ~/psut-wsl/activate.sh
    cd ~/psut-wsl/labs/python/lab37 && python echo_client.py
    ✓ Expected: Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected. If successful, client: Server replied: ACK temp=24.5 · server: Connected by ('127.0.0.1', …) , Received: temp=24.5 .
    Expected result for each action (2)
    1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
    2. cd ~/psut-wsl/labs/python/lab37 && python echo_client.pyNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected. If successful, client: Server replied: ACK temp=24.5 · server: Connected by ('127.0.0.1', …) , Received: temp=24.5 .
    Checkpoint client: Server replied: ACK temp=24.5 · server: Connected by ('127.0.0.1', …) , Received: temp=24.5 .
    03

    Connections

    WSL · Bash
    ss -ltn | grep ":5000"
    ✓ Expected: Socket table appears; check the required protocol, port and connection state. Empty results may be normal without active connections.
    Checkpoint the established connection on port 5000 while the client runs.
    04

    LAN version (lan_tcp_server.py)

    Needs mirrored networking (overview, step 3). Replace 192.168.1.20 with your hostname -I address; allow Python through Windows Firewall when asked.

    Checkpoint a client on another PC connects. (not run here: needs Internet / your account)
    05

    If “Address already in use”

    An old server still holds port 5000: ss -ltnp | grep 5000 , stop it with Ctrl+C in its terminal (or wait a few seconds).

    Checkpoint the server starts.
    06

    Stop background processes

    After the client finishes, press Ctrl+C in each server/receiver terminal. If a port is busy, inspect it with ss -ltnp or ss -lunp; stop your own earlier terminal, not an unrelated service.

    Checkpoint Complete the action before continuing.

    Experimental notebook

    Record your own results. Values are not prefilled or independently verified.

    03 / Inspect

    Source code and method

    labs/python/lab37/echo_client.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    # ---- TCP client: socket -> connect -> send -> recv
    import socket                       # Python's built-in networking module
     
    SERVER = '127.0.0.1'                # server IP (here: this same computer)
    PORT = 5000                         # must match the server's port
     
    # Create a TCP/IPv4 socket for the client side.
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
        client.connect((SERVER, PORT))            # handshake with the server
        client.sendall('temp=24.5'.encode())      # text -> bytes, then send
        reply = client.recv(1024)                 # wait for the answer
        print('Server replied:', reply.decode())  # bytes -> text
    
    labs/python/lab37/echo_server.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # 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
    
    labs/python/lab37/lan_tcp_client.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    # ---- Runs on sensor node room-101  (IP 192.168.1.31)
    import socket
     
    # TCP/IPv4 socket for the node (client side).
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as c:
        c.connect(('127.0.0.1', 5000))    # gateway IP + port (handshake)
        print('My end   :', c.getsockname())  # port chosen by the OS
        print('Other end:', c.getpeername())  # the gateway's IP and port
        c.sendall(b'room-101,24.5')          # 13 bytes of data
        print('Reply:', c.recv(1024).decode())
    
    labs/python/lab37/lan_tcp_server.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    # ---- Runs on the Raspberry Pi gateway  (IP 192.168.1.20)
    import socket
     
    # TCP/IPv4 socket; "with" closes it automatically at the end.
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srv.bind(('192.168.1.20', 5000))     # this Pi's IP, fixed port 5000
        srv.listen()                         # wait for nodes to connect
        print('Listening on', srv.getsockname())
        conn, addr = srv.accept()            # blocks until a node connects
        with conn:
            print('Connection from', addr)   # node IP + its temporary port
            print('Server side  :', conn.getsockname())
            data = conn.recv(1024)           # up to 1024 bytes
            print('Received', len(data), 'bytes:', data.decode())
            conn.sendall(b'ACK')             # confirm receipt
    
    04 / Verify

    Evidence of completion

    Save the actual terminal output from the checkpoints above. For simulated inputs explicitly record browser model, fakepi, mock or Wokwi. Never present those data as physical measurements. If a checkpoint fails, see the troubleshooting guide.

    Python / Google Colab laboratory

    P37 · 9 notebook cells · 2 executable Python cells

    Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

    How to execute

    1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
    2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
    3. Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.

    Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

    01Instructions · Markdown
    # p37 · Lab 37 · TCP echo server and client **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Establish a TCP echo exchange and verify its acknowledgment. ## How to run 1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook. 2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all. 3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell. 4. Save your own outputs and compare them to the portal Experiment tab. **Execution boundary:** Actual local loopback exchange with bounded sockets; no external network. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
    02Instructions · Markdown
    ## Experiment-specific preparation Establish a TCP echo exchange and verify its acknowledgment. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Run the buffered receiver with 3-byte reads. Inspect each partial buffer and emitted complete line. 2. Select one recv = one message and compare parsed message count and correctness. 3. Restore buffered parsing; set recv size to 20. Confirm two messages can arrive in one read. 4. Run the corresponding local TCP client/server source and verify stream framing independently. **Evidence:** **Boundary:**
    03Instructions · Markdown
    ## 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implemented, and explain any discrepancy. - Distinguish actual local Python execution from mock, physical and external-service observations. ## 2. Environment check
    04Python · executable cell
    PYTHON · Code cell
    # =====================================================================
    # P37 | Code cell 01 | Lab 37 · TCP echo server and client
    # Purpose: 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implem
    # Inputs: the explicit fixture/settings below and any preceding cell state.
    # Output: inspect printed values, returned records or assertions; record evidence.
    # =====================================================================
    import sys
    print("Python",sys.version.split()[0])
    # Check the expected invariant so a mismatch fails visibly instead of appearing successful.
    assert sys.version_info >= (3,10)
    
    Ask Dr. Mohammad about this cell
    05Instructions · Markdown
    ## 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
    06Python · executable cell
    PYTHON · Code cell
    # =====================================================================
    # P37 | Code cell 02 | Lab 37 · TCP echo server and client
    # Purpose: 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
    # Inputs: the explicit fixture/settings below and any preceding cell state.
    # Output: inspect printed values, returned records or assertions; record evidence.
    # =====================================================================
    import socket,threading
    # Actual loopback exchange; ephemeral port avoids collision with other labs.
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
        server.bind(('127.0.0.1',0)); server.listen(1);server.settimeout(3)
        with socket.create_connection(server.getsockname(),timeout=3) as client:
            conn,_=server.accept()
            with conn:
                conn.settimeout(3);client.sendall(b'temp=24.5');request=conn.recv(1024)
                conn.sendall(b'ACK '+request);reply=client.recv(1024)
                assert reply==b'ACK temp=24.5';print(reply.decode())
    
    Ask Dr. Mohammad about this cell
    07Instructions · Markdown
    ## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/python/lab37 && python echo_server.py ``` ```bash source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/python/lab37 && python echo_client.py ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- TCP client: socket -> connect -> send -> recv import socket # Python's built-in networking module SERVER = '127.0.0.1' # server IP (here: this same computer) PORT = 5000 # must match the server's port # Create a TCP/IPv4 socket for the client side. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client: client.connect((SERVER, PORT)) # handshake with the server client.sendall('temp=24.5'.encode()) # text -> bytes, then send reply = client.recv(1024) # wait for the answer print('Server replied:', reply.decode()) # bytes -> text ``` ```python # ------------------------------------------------------------ # 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 ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Runs on sensor node room-101 (IP 192.168.1.31) import socket # TCP/IPv4 socket for the node (client side). with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as c: c.connect(('127.0.0.1', 5000)) # gateway IP + port (handshake) print('My end :', c.getsockname()) # port chosen by the OS print('Other end:', c.getpeername()) # the gateway's IP and port c.sendall(b'room-101,24.5') # 13 bytes of data print('Reply:', c.recv(1024).decode()) ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Runs on the Raspberry Pi gateway (IP 192.168.1.20) import socket # TCP/IPv4 socket; "with" closes it automatically at the end. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind(('192.168.1.20', 5000)) # this Pi's IP, fixed port 5000 srv.listen() # wait for nodes to connect print('Listening on', srv.getsockname()) conn, addr = srv.accept() # blocks until a node connects with conn: print('Connection from', addr) # node IP + its temporary port print('Server side :', conn.getsockname()) data = conn.recv(1024) # up to 1024 bytes print('Received', len(data), 'bytes:', data.decode()) conn.sendall(b'ACK') # confirm receipt ```
    08Instructions · Markdown
    ## 4. Results and analysis Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result. | Trial | Configuration | Observation | Interpretation | |---|---|---|---| | A | Reference | | | | B | One controlled change | | | | C | Reference repeat | | | **Limitations:** Actual local loopback exchange with bounded sockets; no external network. Notebook success does not certify external equipment or services.
    09Instructions · Markdown
    ## Guided reasoning and evidence A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above. **Independent task:** 2. Select one recv = one message and compare parsed message count and correctness. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat. | Trial | Input/configuration | Prediction | Observation | Evidence / limitation | |---|---|---|---|---| | A | Reference | | | | | B | Changed input | | | | | A repeat | Reference | | | | A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.