A persistent connection keeps one TCP connection available for multiple HTTP requests instead of opening a new connection for each request. Reusing it removes repeated connection-establishment overhead and improves web-client performance, which matters when a robot needs responsive remote control. section 5.6.3 section 5.7
Create one Python `HTTPConnection` for the robot host and port, then pass that connection into reusable request functions. Each call JSON-encodes its arguments, sends a POST request, and reads the response before the same connection is used for the next movement. section 5.6.3
A reusable client separates the work into small pieces:
- `call_api(conn, url, data)` encodes request data as JSON, sends a POST request through `conn`, and consumes the response. section 5.6.3
- `call_robot(conn, func, **args)` turns a movement name and arguments into a URL and request body. section 5.6.3
- A single `HTTPConnection('robopi:8888')` can issue repeated `spin_right` and `spin_left` calls at several speeds. section 5.6.3
Drive several robot movements through one connection
Open the connection once, then call `spin_right` and `spin_left` for speeds 1, 2, and 3. The physical result is a robot that spins in both directions at each configured speed without reconnecting for every web-service call. section 5.6.3
Listing 5.6 client_persist.py: Using persistent connections to call web services
#!/usr/bin/env python3
from http.client import HTTPConnection
import json
def call_api(conn, url, data):
body = json.dumps(data).encode()
conn.request('POST', url, body)
with conn.getresponse() as resp:
resp.read()
def call_robot(conn, func, **args):
return call_api(conn, '/' + func, args)
conn = HTTPConnection('robopi:8888')
for speed in [1, 2, 3]:
call_robot(conn, 'spin_right', speed=speed)
call_robot(conn, 'spin_left', speed=speed)
This complete client script creates one `HTTPConnection` and routes every movement request through it. section 5.6.3
Measure the benefit rather than assuming it. Time a no-operation (`noop`) service call with `time.perf_counter()`, record the first call separately, then collect 100 later calls on the same connection. Report maximum, average, minimum, and sample standard deviation; these results can be compared with fresh connections, SSH calls, and local or remote network paths. section 5.6.4

