Socket Message Reader

Asked at Apple· Screen

Reported by the problem's creator, not verified

Import another question

A connection delivers bytes in pieces of any size. recv() returns the next piece as a list of integers from 0 to 255, and returns an empty list once the sender has closed the connection. It is provided. Pieces do not line up with messages: a piece can end in the middle of a message or contain several.

Each test builds a reader from a list of pieces and an optional max_size, then calls the methods in order. An operation that raises is recorded as the exception name, and no call is made after one that raised.

Examples

  1. Example 1

    Input: init = [[[0,0,0,3,7],[8,9,0,0,0,1,5]]], operations = [["read_message",[]],["read_message",[]],["read_message",[]]]

    Output: [[7,8,9],[5],null]

    Explanation: The first piece holds the header (length 3) and one payload byte; the second piece supplies the other two bytes and the start of the next message, whose length is 1. The reader keeps the leftover bytes between calls. After the second message the sender has closed with nothing pending, so the third call returns None.

  2. Example 2

    Input: init = [[[104,105,13],[10,111,10]]], operations = [["read_line",[]],["read_line",[]],["read_line",[]]]

    Output: [[104,105],[111],null]

    Explanation: The first line is the bytes hi; its CR arrives at the end of one piece and the LF at the start of the next, and both are dropped. The second line is o. Then the sender has closed with nothing pending, so None.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.