Each message starts with a two-digit length (the number of characters after it). The chunks can cut the stream anywhere, even inside the length.
What to build
A program that finds all complete messages in a chunked stream.
Requirements
- Keep a buffer of what has arrived. Whenever it holds a full length prefix (2 digits) and all the characters it announces, print
message: TEXTand remove that message from the buffer. A length of00is an empty message: printmessage:. - Repeat until the buffer holds no complete message, then take the next chunk.
- After the last chunk, if the buffer is not empty print
partial: TEXT, showing everything left (including an incomplete length).
Input
A line with n, then n lines, each one chunk of the stream (never empty).
Output
message: lines and possibly one partial: line.
Constraints
1 ≤ n ≤ 30; the stream is made only of valid messages (but may stop part-way).
Example
Input:
4
05he
llo03
abc02h
i
Output:
message: hello
message: abc
message: hi
Why it works
The receiver cannot tell where a message ends until its length is known, and the length itself may be incomplete. A buffer that is only consumed when a whole message is present handles every way of cutting the stream.
Examples
4 05he llo03 abc02h i
message: hello message: abc message: hi
2 05hello 03ab
message: hello partial: 03ab
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Add each chunk to a buffer. While the buffer has at least 2 characters, read the length L from the first two.
Hint 2
If the buffer holds at least 2 + L characters, the message is buffer[2:2 + L]; remove 2 + L characters and look again. Otherwise wait for the next chunk.
Hint 3
The two length digits may arrive in separate chunks. At the end, anything left in the buffer is a partial message.
Solution
Show one correct solution (try it yourself first)
n = int(input())
buffer = ""
for _ in range(n):
buffer += input()
while len(buffer) >= 2 and len(buffer) >= 2 + int(buffer[:2]):
size = int(buffer[:2])
print("message: " + buffer[2:2 + size])
buffer = buffer[2 + size:]
if buffer:
print("partial: " + buffer)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step