Testing TCP half-close: EOF, response reads and timeout boundaries

Testing TCP half-close: EOF, response reads and timeout boundaries

Testing TCP half-close: EOF, response reads and timeout boundaries

A batch client has finished sending its input, but the server is stuck in its read loop while the client keeps waiting for a result. A packet capture shows the data arriving, yet the application reports no error. This failure is common in custom protocols that wait for end-of-input before processing: neither side has agreed on how to end the request, so both end up waiting for each other. Reproducing the send-side and receive-side states locally on the dedicated server, then checking the application code, is a more effective way to locate the problem than simply increasing a timeout.

Separate end-of-send from connection closure

TCP is a bidirectional byte stream. When a client's sendall() call returns, it means only that the data has been handed to the local protocol stack. It does not prove that the server has read it, much less that application processing succeeded. Nor does one server-side recv() call correspond to one send operation. A short read cannot serve as an end-of-request marker.

Calling shutdown(socket.SHUT_WR) closes the sending direction. Data already sent is still delivered in TCP order; once the server has read it all, it receives an empty byte string, or EOF. The client can still read the server's response. This is a half-close, not the same as closing the entire socket.

EOF marks end-of-input at the transport layer, not successful application processing. The request must be validated before an explicit result is returned, and the client must read and verify that result.

This article tests only a custom protocol over plaintext TCP. Do not apply the procedure directly to HTTP, TLS, or existing messaging protocols. Those protocols have their own rules for lengths, message endings, and connection closure. Adding a half-close at the underlying layer without regard for those rules can disrupt the protocol state.

Define the isolated test boundary

Prepare Python 3 on Ubuntu Server 24.04 LTS and save the following program as halfclose_lab.py. The program listens only on the loopback address, using a temporary port assigned by the operating system. It does not change the firewall or connect to application services. No administrator privileges are required.

The test protocol handles one request per connection. Input ends at EOF and is limited to 1024 bytes. A successful response returns the number of bytes received; if the read timeout expires before EOF arrives, the server returns an error. The response also ends when the server closes its sending direction.

The timeout here only ensures that the local negative test finishes promptly; it is not a production setting. Production systems also need an overall request deadline so that a peer cannot keep sending small amounts of data and repeatedly restart the timeout for each read. The input limit must likewise be defined by application requirements, not copied from this experiment.

Run the positive and negative tests

import socket
import threading

LIMIT = 1024
PAYLOAD = b"prompt\n"


def serve(listener):
    with listener:
        conn, _ = listener.accept()
        with conn:
            conn.settimeout(0.5)
            body = bytearray()
            reply = None
            try:
                while True:
                    part = conn.recv(min(256, LIMIT + 1 - len(body)))
                    if not part:
                        reply = f"OK {len(body)}\n".encode("ascii")
                        break
                    body.extend(part)
                    if len(body) > LIMIT:
                        reply = b"ERR too-large\n"
                        break
            except socket.timeout:
                reply = b"ERR eof-required\n"
            conn.sendall(reply)
            conn.shutdown(socket.SHUT_WR)


def run_case(half_close):
    listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listener.bind(("127.0.0.1", 0))
    listener.listen(1)
    address = listener.getsockname()
    worker = threading.Thread(target=serve, args=(listener,), daemon=True)
    worker.start()

    with socket.create_connection(address, timeout=3) as client:
        client.sendall(PAYLOAD)
        if half_close:
            client.shutdown(socket.SHUT_WR)
        response = bytearray()
        while True:
            part = client.recv(256)
            if not part:
                break
            response.extend(part)

    worker.join(timeout=3)
    assert not worker.is_alive()
    return bytes(response)


assert run_case(True) == b"OK 7\n"
assert run_case(False) == b"ERR eof-required\n"

Run python3 halfclose_lab.py. Both paths pass only if the program exits normally with no assertion failures. No output is the fixture's expected behavior. If a thread raises an exception, a read times out, or an assertion fails, retain the full exception details. Do not remove a failing assertion just to make the test pass.

The positive path sends seven bytes, then closes the sending direction. After reading EOF, the server generates OK 7, and the client keeps reading until the response ends. The negative path sends the same content but does not signal completion. The server cannot infer a complete request from “no data available right now,” so it returns ERR eof-required.

Verify the response read loop

The client receives the response in a loop rather than calling recv() just once. Even if the local experiment usually delivers the entire result in one read, that observation must not be treated as a protocol guarantee. Network segmentation, scheduling, and changes in buffering can all cause the response to arrive across multiple reads.

The fixture's length check only demonstrates the point at which input is rejected. If the peer keeps sending after exceeding the limit, the server's connection closure may cause a reset, and delivery of the error text is not guaranteed. A production rejection path must stop application processing and define whether to drain the remaining input. It must neither drain indefinitely nor assume that the error text will be read.

Reproduce the failure and interpret the results

Keep the positive case first, then examine the negative case that omits the half-close. An explicit timeout error demonstrates that the server really is waiting for EOF rather than mistaking the bytes currently available for a complete request. If the server succeeds without a half-close, check whether it has silently switched to using a short read, a newline, or the buffer length as its end condition.

Do not replace the half-close with close() to “fix” the client. Once the socket is closed, the application no longer has its normal path for reading the response. Even if the server completes processing, the client cannot confirm the result. Successful sending and an unknown processing outcome must be recorded separately. In particular, never automatically repeat a non-idempotent task when its outcome is unknown.

Do not treat a read timeout as a normal end-of-input either. A pause in sending, connection jitter, and actual completion have different application-level meanings. Treating a timeout as success passes truncated input on for further processing. A connection reset must likewise follow the failure path, not be converted into an empty request.

Empty input requires a separate decision. This fixture accepts it and returns OK 0 solely to highlight the byte-stream boundary. If the application does not allow empty requests, add a content check after EOF and an assertion verifying rejection. A nonzero input length is not a substitute for checking completeness.

Finalize production acceptance checks

Keep at least four pieces of evidence in the test record: the byte length of a known input, the complete response after the half-close, an explicit failure when the end signal is missing, and confirmation that no worker thread remains after the connection ends. Length is measured in bytes; a count of Chinese characters cannot be used directly as the network payload length.

Add tests against the real service for empty input, oversized input, input sent in chunks, and a client that exits early. To test chunked sending, split the same payload across multiple sendall() calls. The final reported length must remain unchanged. The response receiver should also enforce a limit on the total bytes received so that a faulty service cannot return data indefinitely.

If the application needs to handle multiple requests on the same connection, it should not rely on EOF to delimit each one. Use explicit lengths or message boundaries instead, and verify request completion separately from the connection lifecycle. A half-close suits an established “one input, one result” contract; it is not a substitute for connection reuse.

Final acceptance depends on the application outcome: input ended unambiguously, processing did not accept truncated data, the response was read in full, and error paths terminated as failures. Only when all four conditions hold can “the data has been sent” become “this exchange is complete.”

Frequently asked questions

Can a client read a response after shutdown(SHUT_WR)?

Yes. It closes only the sending direction. Keep reading the response, validate the application result, and then close the socket.

Does receiving EOF mean a request succeeded?

No. EOF only indicates that the peer has ended its sending direction. The server must validate the input and return an explicit application result.

AMD EPYC 7543P Dedicated Server

From $446/month

Configure a Dedicated Server

Choose memory, storage, bandwidth, and OS to suit the workload. The configuration page shows the amount due for the current billing period.