Messages on a TCP stream
TCP carries a stream of bytes, not messages: two writes can arrive as one read, and one write as two. A protocol that sends messages must say where each one ends. This lesson adds a length prefix, reads exactly n bytes with a buffer, handles partial reads, sends empty and binary messages and refuses a length that is too big.
What you will learn#
- why TCP has no message boundaries,
- a length prefix: four bytes in network order (big endian),
Readthat returns fewer bytes than asked, and reading exactly n bytes in a loop,- sending text, binary, empty and long messages,
- several messages written together and read one by one,
- a maximum length that protects the receiver.
The tutorial Sockets sent a few lines over TCP. Real protocols (chat, file transfer, a database) send many messages of different sizes.
The program#
# messages on a TCP stream - TCP has no message boundaries: a length prefix, reading exactly n bytes, partial reads and a limit
load "dotnet.ring"
using {
"System"
"System.Net"
"System.Net.Sockets"
}
func main
# TCP is a STREAM of bytes, not a list of messages. If a program writes "ab" and then "cd", the other side may read "abcd" in one call,
# or "a" and "bcd", or ... The sizes of the pieces that Read returns have nothing to do with the sizes of the writes. A protocol that
# sends MESSAGES must say where each one ends: here every message has a LENGTH PREFIX, four bytes with the size of the message,
# and then the message itself.
oListener = new TcpListener(new IPAddress().Loopback,0)
oListener.Start(NULL)
oClient = new TcpClient().@New([ :hostname = "127.0.0.1", :port = oListener.LocalEndpoint.Port ])
oServerSide = oListener.AcceptTcpClient()
oSender = oClient.GetStream()
oReceiver = oServerSide.GetStream()
? "1. connected"
# 2. The length as four bytes (big endian: the biggest byte first, the order of the network)
? nl + "2. the length as four bytes:"
for nLength in [ 0, 5, 300, 40000 ]
? " " + padLeft("" + nLength,6) + " -> " + hexText(lengthBytes(nLength))
next
? " decoded again: " + bytesLength(lengthBytes(40000))
# 3. Messages: text, bytes that are not text (a NUL and a byte over 127), an empty message, and a long one. Each is written as ONE
# message, and read back as one message, whatever the pieces of the TCP stream were.
? nl + "3. messages through the stream:"
aMessages = [ "hello", "a" + char(0) + "b" + char(255), "", copy("0123456789",4000) ]
for cMessage in aMessages
writeMessage(oSender,cMessage)
aResult = readMessage(oReceiver,100000)
? " sent " + padLeft("" + len(cMessage),5) + " bytes, received " + padLeft("" + len(aResult[1]),5) + " bytes; the same: " + yesNo(aResult[1] = cMessage)
next
# 4. Several messages written together: the receiver still gets them one by one
writeMessage(oSender,"one")
writeMessage(oSender,"two")
writeMessage(oSender,"three")
? nl + "4. three messages written together are read as: " + readMessage(oReceiver,1000)[1] + ", " + readMessage(oReceiver,1000)[1] + ", " + readMessage(oReceiver,1000)[1]
# 5. A limit. The length comes from the network, so it can be anything: 4 gigabytes would make the receiver allocate 4 gigabytes.
# A protocol has a maximum, and a message with a bigger length is refused before any memory is used.
oSender.Write(lengthBytes(50000000),0,4)
? nl + "5. a message that claims 50,000,000 bytes (the limit is 1,000): " + readMessage(oReceiver,1000)[1]
oClient.Close()
oServerSide.Close()
oListener.Stop()
# the length as four bytes, biggest first
func lengthBytes nLength
return char(floor(nLength / 16777216) % 256) + char(floor(nLength / 65536) % 256) + char(floor(nLength / 256) % 256) + char(nLength % 256)
func bytesLength cBytes
return ascii(substr(cBytes,1,1)) * 16777216 + ascii(substr(cBytes,2,1)) * 65536 + ascii(substr(cBytes,3,1)) * 256 + ascii(substr(cBytes,4,1))
# one message: the length, then the bytes. Two writes (a real program may write both in one buffer).
func writeMessage oStream,cMessage
oStream.Write(lengthBytes(len(cMessage)),0,4)
if len(cMessage) > 0
oStream.Write(cMessage,0,len(cMessage))
ok
# Read EXACTLY nCount bytes. A single Read may give fewer bytes than were asked for (the rest has not arrived yet), so the program reads
# again, into the next part of the same buffer, until all the bytes are there. Read gives 0 when the other side has closed the connection.
# The answer is [the bytes, the number of Read calls].
func readExact oStream,nCount
if nCount = 0
return [ "", 0 ]
ok
oBuffer = dnBuffer(nCount)
nGot = 0
nCalls = 0
while nGot < nCount
nRead = oStream.Read(oBuffer,nGot,nCount - nGot)
nCalls++
if nRead = 0
raise("the connection was closed in the middle of a message")
ok
nGot += nRead
end
return [ dnBufferBytes(oBuffer,nCount), nCalls ]
# One message: read the four bytes of the length, check it against the maximum, then read the message. The answer is [the message, the
# number of Read calls: it depends on how the bytes arrived, so the program does not print it], or ["(refused: ...)", 0] for a length over the maximum.
func readMessage oStream,nMaximum
aHeader = readExact(oStream,4)
nLength = bytesLength(aHeader[1])
if nLength > nMaximum
return [ "(refused: " + nLength + " bytes is more than " + nMaximum + ")", 0 ]
ok
aBody = readExact(oStream,nLength)
return [ aBody[1], aHeader[2] + aBody[2] ]
func hexText cBytes
cText = ""
for i = 1 to len(cBytes)
cText += right("0" + upper(hex(ascii(substr(cBytes,i,1)))),2) + " "
next
return trim(cText)
func yesNo lValue
if lValue
return "yes"
ok
return "no"
func padLeft cText,nWidth
return copy(" ",nWidth - len(cText)) + cText1. connected
2. the length as four bytes:
0 -> 00 00 00 00
5 -> 00 00 00 05
300 -> 00 00 01 2C
40000 -> 00 00 9C 40
decoded again: 40000
3. messages through the stream:
sent 5 bytes, received 5 bytes; the same: yes
sent 4 bytes, received 4 bytes; the same: yes
sent 0 bytes, received 0 bytes; the same: yes
sent 40000 bytes, received 40000 bytes; the same: yes
4. three messages written together are read as: one, two, three
5. a message that claims 50,000,000 bytes (the limit is 1,000): (refused: 50000000 bytes is more than 1000)How it works#
A stream, not a list of messages#
If a program writes ab and then cd, the other side may read abcd at once, or a and bcd: the operating system splits and joins the bytes as it likes, and a read gives what has arrived so far. A program that assumes one write is one read works on the test computer and fails on a slow network or with a long message. The receiver needs to be told where a message ends.
The length prefix#
Each message starts with its length in four bytes, biggest byte first (the order of the network, called big endian): 300 is 00 00 01 2C (1 × 256 + 44). The receiver reads four bytes, decodes the length, and then reads exactly that many bytes. lengthBytes and bytesLength convert in both directions with char and ascii; a Ring text holds the bytes. Other ways to mark the end exist (a line ending, a special byte), but a length works for any data, including bytes that look like the marker.
Exactly n bytes#
Read(buffer, offset, count) returns the number of bytes that it wrote, which can be less than count: the rest has not arrived yet. readExact makes a buffer of the size that it needs and calls Read again and again, each time into the next part of the same buffer (offset = nGot, count = nCount - nGot), until all the bytes are there. A Read that returns 0 means that the other side closed the connection, and in the middle of a message that is an error, which the function raises.
The messages#
The program sends a text, a message with a NUL and a byte over 127, an empty message (the length is 0 and there is nothing more to read) and one of 40,000 bytes, and each comes back as it was sent. A Ring text can hold the bytes, and dnBuffer gives Read an array to fill. Step 4 writes three messages one after the other and reads them one by one: the boundaries come from the lengths and not from the writes.
A limit#
The length is a number from the network, so it can be anything. A message that says that it has 50,000,000 bytes makes a careless receiver allocate that much memory, which is a way to stop a server (a denial of service). readMessage has a maximum and refuses a bigger length before it allocates anything. The sender of a real protocol is also checked (and the connection is closed after the refusal, because the bytes that follow can not be understood any more).
The test sends and reads in one program on one thread, so a message must fit in the buffers of the connection (about 64 KB) or Write would wait for a reader that never starts. A real client and server run in separate programs or threads.
What you learned#
- TCP is a stream and needs a protocol for messages,
- a length prefix in big endian,
- reading exactly n bytes into a buffer, with partial reads,
- empty and binary messages,
- a maximum length.
Exercises#
- Add a message type (one byte) after the length:
Tfor text andBfor binary. - Write
writeMessageso that it sends the length and the message in one write (join them first). - Make the receiver close the connection after a refused length and tell the sender.
- Add a checksum (four bytes of
CRC32or the start of a SHA-256) after each message and check it.