Delimiting "one message" in TCP: Trying length prefixes on localhost

ネットワーク・RFCカテゴリを表すパンダのイラスト Networking / RFC

About this article
This article was created using an automated generation workflow powered by generative AI. It reviews RFC 9293 and the .NET Socket API, organizing the concept of attaching length information to a TCP byte stream into an observable format on localhost.

Verification status: 📘 RFC and .NET official specifications checked, actual hardware not verified

TCP does not have application message boundaries. Therefore, we will experience a length prefix—where "how many bytes come next" is placed before the body—using minimal data.

Try it first

$msg='HELLO'
$body=[Text.Encoding]::UTF8.GetBytes($msg)
$prefix=[BitConverter]::GetBytes([Net.IPAddress]::HostToNetworkOrder($body.Length))
"prefix=$([BitConverter]::ToString($prefix)) body=$msg"
$len=[Net.IPAddress]::NetworkToHostOrder([BitConverter]::ToInt32($prefix,0))
"receiver expects $len bytes"

Look here

Before reading the body, the receiving side can know5 bytes.SendorReadThe key point is that the application itself defines the boundaries, rather than the number of times

Change one part

HELLOtoこんにちはand verify that the UTF-8byte count, rather than the character count, becomes the prefix.

Why this happens

TCP guarantees an ordered byte stream. Framing mechanisms such as fixed lengths, delimiters, or length prefixes are the responsibility of the upper layer protocol.

graph LR
L[4-byte length] --> B[payload bytes]
B --> R[receiver reads exactly length]

If used in production

In implementations, you must also consider cases where the prefix itself is received in fragments, requiring logic to "read until 4 bytes are accumulated" and "read until the declared length is accumulated." Also, set an upper limit rather than unconditionally allocating huge declared lengths.

RFC 9293: https://www.rfc-editor.org/rfc/rfc9293

Microsoft NetworkStream.Read: https://learn.microsoft.com/dotnet/api/system.net.sockets.networkstream.read

Document information

Article title
Delimiting "one message" in TCP: Trying length prefixes on localhost
Published
Updated
Source
https://papanda925.com/?p=15439&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL