Reassemble newline-delimited application messages from arbitrary TCP read chunks.
The focus of this experiment is to trace a TCP humidity request through server and client state. Students then interpret stream framing and read boundaries, and verify delivered readings and handle disconnects. 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 a TCP humidity request through server and client state.
Interpret stream framing and read boundaries.
Verify delivered readings and handle disconnects.
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 a TCP humidity request through server and client state, interpret stream framing and read boundaries, and verify delivered readings and handle disconnects.
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 delivered readings and handle disconnects. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to Lab 15 · UDP humidity server & client.
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.
X14 / 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.
TCP humidity telemetry is an ordered stream; byte chunking is unrelated to sample boundaries.
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 · Humidity telemetry over TCP
TCP delivers a reliable ordered stream, but application records need framing and validation. A connection may close before a full final record is received; timeouts are not proof of a sensor fault. A receiver should parse only complete records using the lab's delimiter or defined format.
Worked example and engineering interpretation
Two readings sent consecutively can arrive together in one recv call; a split record may arrive in several calls. The number of socket reads is therefore not the number of humidity samples. Test partial and multiple records, and preserve the correct units.
Engineering principles · additional worked teaching example
TCP humidity readings need delimiter-based parsing and numeric validation. For complete lines 40,60 and one invalid, mean50% RH over two accepted samples. A received chunk may contain half a decimal or multiple readings.
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 14 · TCP humidity server & client
TCP humidity request/response using a real loopback socket and fictional sensor value. TCP is a byte stream and newline frames the request.
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: Exchange mock humidity measurements over TCP.
Run the buffered receiver with 3-byte reads. Inspect each partial buffer and emitted complete line.
Select one recv = one message and compare parsed message count and correctness.
Restore buffered parsing; set recv size to 20. Confirm two messages can arrive in one read.
Run the corresponding local TCP client/server source and verify stream framing independently.
Reference check:
Model boundary:
Independent task and submission evidence
Replace GET_HUMIDITY with BAD and update the expected assertion to check the error response. Record the response and explain the TCP message boundary and timeout.
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.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
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.
Step 1 of 4 · "55." →
"55." →
1. TCP stream → Parser
"55." →
"0\n5" → 55.0
1. TCP stream → Parser
"55." →
2. TCP stream → Parser
"0\n5" → 55.0
"6.0" →
1. TCP stream → Parser
"55." →
2. TCP stream → Parser
"0\n5" → 55.0
3. TCP stream → Parser
"6.0" →
"\n" → 56.0
1. TCP stream → Parser
"55." →
2. TCP stream → Parser
"0\n5" → 55.0
3. TCP stream → Parser
"6.0" →
4. TCP stream → Parser
"\n" → 56.0
Teaching example only; inspect live calculations or real practical evidence separately.
Recall the concept before revealing its explanation.
0 / 3 revealed
X14 · 01 / 08What does TCP provide?Reveal explanation
Engineering explanation
An ordered byte stream for the humidity request and response.
X14 · 02 / 08What proves the server works?Reveal explanation
Engineering explanation
The client receives a parseable response from the matching local port.
X14 · 03 / 08What listener and client conditions must be checked before TCP transfer?Reveal explanation
Engineering explanation
Keep server in Terminal 1 and client in Terminal 2; verify port 20001, then stop the server. Use synthetic values only.
X14 · 04 / 08Why keep the server running during the client test?Reveal explanation
Engineering reasoning
The client needs a listening endpoint; stopping the server removes the service being tested.
A successful TCP exchange does not prove that expected humidity fields or values were received.
X14 · 06 / 08A TCP humidity exchange uses mock data. Select every technically valid statement.
A. Validate framing and numeric fields.
B. Label humidity as mock input in the evidence.
C. TCP converts mock data into measured humidity.
D. A socket read necessarily returns one complete application record.Reveal explanation
Applied scenario
Correct: A. Validate framing and numeric fields.; B. Label humidity as mock input in the evidence.
X14 · 07 / 08In TCP humidity server & client, which command or code executes Terminal 2: client?Reveal explanation
Implementation recall
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
python -m labs.exp14.client
X14 · 08 / 08For TCP humidity server & client, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance
Run server in A from pi-practical; B runs client. Expected JSON includes sensor_id, timestamp, temperature, humidity and source mock (default initial 23.0 C/63.0%). Stop continuous server A or use --once for one controlled exchange. Port 20001 is loopback.
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.
Independent conceptual protocol trace
Animated Lab 14 · TCP humidity server & 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 eventsShared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery researchLoading experiment-specific apparatus…Previous model / additional reference tools
Simulation task
Exchange mock humidity measurements over TCP.
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 workbenchX14 · Existing model
01 / Explore
Interactive lab simulation
Browser model
Pin and connection reference
WSL uses simulated GPIO. These are source-derived signal mappings; physical connection notes are guidance, not a claim of physical testing.
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.
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.
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 mock humidity request/response passed.
Run server in A from pi-practical; B runs client. Expected JSON includes sensor_id, timestamp, temperature, humidity and source mock (default initial 23.0 C/63.0%). Stop continuous server A or use --once for one controlled exchange. Port 20001 is loopback.
Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.
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 55\n63\n into chunks of at most three bytes; identify complete records and calculate mean humidity.
Engineering method — TCP humidity readings need delimiter-based parsing and numeric validation. For complete lines 40,60 and one invalid, mean50% RH over two accepted samples. A received chunk may contain half a decimal or multiple readings. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Compare or justify using evidence
Predict behavior for an incomplete final record and explain why application framing is required despite TCP reliability.
Engineering method — TCP humidity readings need delimiter-based parsing and numeric validation. For complete lines 40,60 and one invalid, mean50% RH over two accepted samples. A received chunk may contain half a decimal or multiple readings. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Parsing exercise — TCP humidity readings need delimiter-based parsing and numeric validation. For complete lines 40,60 and one invalid, mean50% RH over two accepted samples. A received chunk may contain half a decimal or multiple readings. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
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 · X14-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 = 2. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.
Intermediate · Quantitative comparison
Independent theoretical exercise · X14-02
Two model observations of recv calls are 4 (reference) and 2 (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 · X14-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 · "55." · 55. · ""
3 · "0\n5" · 0
5 · ""
6 · "6.0" · 6.0 · ""
9 · "\n" · · ""
Count rows whose Received bytes value is exactly “"55."”, and identify the displayed row numbers. Explain what the count describes.
Advanced · Reverse reasoning
Independent theoretical exercise · X14-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 · X14-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 · X14-06
Design a controlled comparison for Lab 14 · TCP humidity server & 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
Run the buffered receiver with 3-byte reads. Inspect each partial buffer and emitted complete line.
Select one recv = one message and compare parsed message count and correctness.
Restore buffered parsing; set recv size to 20. Confirm two messages can arrive in one read.
Run the corresponding local TCP client/server source and verify stream framing independently.
3 · Compare controlled trials
Trial
Independent change
Expected check
Observation
Buffered parsing
Use reference inputs above
Correct messages: 2
Record actual result
Small chunks naive
Receiver strategy = one recv = one message
Correct messages: 0
Record actual result
Single coalesced recv
Bytes per simulated recv() = 20
Correct messages: 2
Record 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.
Trial
Independent change
Dependent observation
Buffered parsing
Use reference inputs above
Record actual outcome and units
Small chunks naive
Receiver strategy = one recv = one message
Record actual outcome and units
Single coalesced recv
Bytes per simulated recv() = 20
Record 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
Original shared humidity protocol and mock acquisition; network transport separately verified by portal tests. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.
Keep server in Terminal 1 and client in Terminal 2; verify port 20001, then stop the server. Use synthetic values only.
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
WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
python-m labs.exp14.server --mock
✓ Expected: TCP listening on 127.0.0.1:20001; keep the server running.Expected result for each action (3)
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.
cd ~/psut-wsl/labs/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
python-m labs.exp14.server --mockTCP listening on 127.0.0.1:20001; keep the server running.
Checkpoint TCP listening ('127.0.0.1', 20001)
02
Terminal 2: client
WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
python-m labs.exp14.client
✓ Expected: A JSON reading containing temperature, humidity and source is received if the matching server is available.Expected result for each action (3)
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.
cd ~/psut-wsl/labs/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
python-m labs.exp14.clientA JSON reading containing temperature, humidity and source is received if the matching server is available.
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.
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.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
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
# X14 · Lab 14 · TCP humidity server & client
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## Theory and purpose
TCP humidity request/response using a real loopback socket and fictional sensor value. TCP is a byte stream and newline frames the request.
**Execution boundary:** local computational model or loopback as explicitly described; not physical measurements or external service certification. Run cells in order.
02Instructions · Markdown
## 1. Define the experiment mechanism and inputs
03Python · executable cell
PYTHON · Code cell
# =====================================================================
# X14 | Code cell 01 | Lab 14 · TCP humidity server & client
# Purpose: 1. Define the experiment mechanism and inputs
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import socket, json
# Set REQUEST for the next computation or reference condition.
REQUEST=b'GET_HUMIDITY'
# Define the reusable operation reply; keep its logic separate from the trial.
def reply(payload):
return json.dumps({'humidity':45.0,'source':'fixture'} if payload==REQUEST else {'error':'bad request'}).encode()
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# X14 | Code cell 02 | Lab 14 · TCP humidity server & client
# Purpose: 2. Execute the reference and inspect observations
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with socket.socket() as server:
server.bind(('127.0.0.1',0));server.listen(1)
with socket.create_connection(server.getsockname(),timeout=2) as client:
conn,_=server.accept()
with conn:
conn.settimeout(2);client.sendall(REQUEST+b'\n')
data=b''
while not data.endswith(b'\n'): data+=conn.recv(1024)
conn.sendall(reply(data.rstrip(b'\n'))+b'\n')
observed=json.loads(client.makefile('rb').readline())
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
print(observed);assert observed['humidity']==45.0
## Independent investigation and submission
Replace GET_HUMIDITY with BAD and update the expected assertion to check the error response. Record the response and explain the TCP message boundary and timeout.
| Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation |
|---|---|---|---|---|---|
| A | baseline | | | | |
| B | one change | | | | |
| A repeat | baseline | | | | |
Save outputs and state one limitation.