A store’s order synchronization service sends tasks over a persistent connection. Local integration tests pass, but after deployment, JSON decoding occasionally fails. Sometimes the receive log contains only part of a message; other times, two messages appear back to back. Before increasing bandwidth or retry counts, check whether the application treats each recv() call as a complete message. TCP delivers an ordered byte stream. The application protocol must define the message boundaries.
1. Define message boundaries in the protocol first
When several services run on the same dedicated server, each TCP connection still needs its own framing rules, even if every service binds to a separate IPv4 address. Address planning cannot replace protocol parsing or prevent message boundaries from becoming misaligned within a connection.
This article uses a four-byte unsigned integer as the header, encoding the length of the following body in network byte order. The length excludes the header. The body may be empty, and its maximum size is 65536 bytes. This is a resource budget for the exercise protocol, not a measure of server performance.
Before sending text, encode it as UTF-8 and then measure the encoded result. The number of Chinese characters is not the number of bytes. Putting a string’s character count in the header will misalign every subsequent frame. The receiver must read the full header, check the size limit, read the body, and only then decode the text or JSON.
One send does not equal one receive. Disabling Nagle’s algorithm, increasing the receive buffer, or adding delays between sends cannot establish reliable message boundaries.
2. Set up a test environment with no public exposure
Prepare Python 3 on Debian 12 or Ubuntu Server 24.04, save the following code as frame_check.py, and run python3 frame_check.py as a regular user. The test uses only local socket pairs. It does not listen on a public address, requires no firewall changes, and does not occupy a service port.
socketpair() is not a real TCP connection, but it provides the byte-stream interface needed for this test. The test also limits each read to at most two bytes, forcing short reads deterministically rather than relying on scheduling or incidental network segmentation. End-to-end validation comes later.
import socket
import struct
MAX_BODY = 65536
def read_exact(sock, size, clean_eof=False):
data = bytearray()
while len(data) < size:
part = sock.recv(size - len(data))
if not part:
if clean_eof and not data:
return None
raise EOFError("truncated frame")
data.extend(part)
return bytes(data)
def read_frame(sock):
header = read_exact(sock, 4, clean_eof=True)
if header is None:
return None
size = struct.unpack("!I", header)[0]
if size > MAX_BODY:
raise ValueError("frame too large")
return read_exact(sock, size)
def encode_frame(body):
if len(body) > MAX_BODY:
raise ValueError("frame too large")
return struct.pack("!I", len(body)) + body
class ShortReader:
def __init__(self, sock):
self.sock = sock
def recv(self, size):
return self.sock.recv(min(size, 2))
def verify(wire, expected=(), error=None):
with socket.socketpair()[0] as unused:
pass
left, right = socket.socketpair()
with left, right:
right.settimeout(1.0)
left.sendall(wire)
left.shutdown(socket.SHUT_WR)
reader = ShortReader(right)
for body in expected:
assert read_frame(reader) == body
if error is None:
assert read_frame(reader) is None
else:
try:
read_frame(reader)
except error:
pass
else:
raise AssertionError("expected failure")
text = "订单同步".encode("utf-8")
verify(encode_frame(text) + encode_frame(b"") + encode_frame(b"ok"),
[text, b"", b"ok"])
verify(b"\x00\x00", error=EOFError)
verify(struct.pack("!I", 5) + b"ab", error=EOFError)
verify(struct.pack("!I", MAX_BODY + 1), error=ValueError)
left, right = socket.socketpair()
with left, right:
right.settimeout(0.1)
try:
read_frame(right)
except socket.timeout:
pass
else:
raise AssertionError("expected timeout")
Do not enable Python’s optimization mode when running the script: it removes assert checks. A normal exit with exit code zero means these assertions passed. An exception traceback means the test failed; “the script ran” is not an acceptance result.
3. Test short reads, consecutive frames, and truncation separately
Check raw bytes on the success path
The first test writes three consecutive frames in a single send: a Chinese-language message, an empty message, and a short message. Although the receiver reads at most two bytes at a time, it must reconstruct the same three byte strings and return None on the next attempt to read a header.
An empty message returns b""; a clean end of the connection returns None. A single truthiness check cannot distinguish them. The application loop should check body is None for termination. Otherwise, it will mistake an empty message for a disconnected peer.
An incomplete frame is not a clean end of stream
The second test contains only two header bytes. The third declares a five-byte body but sends only two bytes. Both must raise a truncation error. EOF is a valid clean end only before a new frame begins, when no header bytes have been read.
The consecutive-frame test verifies that the parser does not depend on send boundaries. The short-read wrapper verifies the read loop. Neither proves that a production network will segment data in any particular way. An acceptance report must not describe local read counts as the number of packets actually received by the network interface.
4. Bound lengths, waiting times, and failure handling
The length field is external input and must not be used directly to allocate an arbitrarily large buffer. The code rejects oversized declarations before reading the body, so a peer can trigger the rejection test by sending only a four-byte header. This check must happen before decoding, decompression, or application processing.
In addition to the per-frame limit, set limits on cumulative processing per connection, connection count, and application queue length. Otherwise, a large number of valid small frames can still exhaust memory. If the body contains compressed content, impose a separate limit on its decompressed size; checking only the transmitted length is not enough.
The example’s timeout limits a single blocking read, not the time allowed to complete an entire frame. A peer that keeps sending small amounts of data slowly can still hold a connection open for a long time. A production implementation should calculate a whole-frame deadline using a monotonic clock and update the wait budget before each read based on the remaining time.
The read function in this article does not preserve partial-frame state across calls. Close the connection after a timeout, truncation, or length error. Catching the exception and calling read_frame() again may interpret the remaining body as a new header, causing a subtler form of data misalignment.
5. Connect parser tests to service acceptance testing
Once the local assertions pass, validate the actual TCP path using an isolated test listener. The test client should cover sending the header in pieces, sending the body in pieces, sending consecutive frames in one operation, and sending only a header before stopping further transmission. Do not inject malformed data directly into a production endpoint.
Keep the following checks when integrating the parser into the application:
- The sender uses
sendall()without assuming that the peer reads everything in one call. - The receiver invokes application processing only after completing a frame, rather than parsing partial text.
- Frames with excessive lengths or decoding errors never enter the application queue.
- Logs record the connection identifier, parsing stage, declared length, and number of bytes received, but not the full order contents.
- A timeout closes the connection, and the processing thread and buffers are confirmed to be released.
- Application retries use a separate request identifier; reconnecting does not automatically make repeated operations safe.
When deploying this type of service on an Evpn dedicated server, check the console for access credentials after payment. Use SSH for Linux administration, and connect to the first address if multiple addresses are assigned. Keep application protocol tests separate from the management connection so that test listeners or misbehaving clients do not interfere with remote administration.
The final acceptance evidence should include the protocol specification, test script, exit status, and error classifications. A reliable conclusion is not that “one receive happened to contain a complete message.” It is that any valid short-read pattern still reconstructs the messages, while all incomplete or out-of-bounds input fails within clearly defined limits.
Frequently asked questions
Does one sendall call guarantee one complete recv?
No. TCP provides an ordered byte stream without preserving send-call boundaries. The receiver must loop until each header and payload is complete and support consecutive frames on the same connection.
Can the receiver read the next frame after a timeout halfway through a message?
This implementation does not retain partial-frame state across calls, so it must close the connection. Restarting at the header could interpret remaining payload bytes as a length. Resuming requires a separate bounded state machine.
AMD EPYC 7543P Dedicated Server
From $457.5/month