Parser is used with StreamParser for incremental protocol parsing. Parser is a generator function, but it is not a coroutine. Usually parsers are implemented as a state machine. more details in asyncio/parsers.py existing parsers: * HTTP protocol parsers asyncio/http/protocol.
(out, buf)
| 19 | |
| 20 | |
| 21 | def my_protocol_parser(out, buf): |
| 22 | """Parser is used with StreamParser for incremental protocol parsing. |
| 23 | Parser is a generator function, but it is not a coroutine. Usually |
| 24 | parsers are implemented as a state machine. |
| 25 | |
| 26 | more details in asyncio/parsers.py |
| 27 | existing parsers: |
| 28 | * HTTP protocol parsers asyncio/http/protocol.py |
| 29 | * websocket parser asyncio/http/websocket.py |
| 30 | """ |
| 31 | while True: |
| 32 | tp = yield from buf.read(5) |
| 33 | if tp in (MSG_PING, MSG_PONG): |
| 34 | # skip line |
| 35 | yield from buf.skipuntil(b'\r\n') |
| 36 | out.feed_data(Message(tp, None)) |
| 37 | elif tp == MSG_STOP: |
| 38 | out.feed_data(Message(tp, None)) |
| 39 | elif tp == MSG_TEXT: |
| 40 | # read text |
| 41 | text = yield from buf.readuntil(b'\r\n') |
| 42 | out.feed_data(Message(tp, text.strip().decode('utf-8'))) |
| 43 | else: |
| 44 | raise ValueError('Unknown protocol prefix.') |
| 45 | |
| 46 | |
| 47 | class MyProtocolWriter: |