|
1 | 1 | # -*- coding: utf-8 -*- |
2 | | -# Copyright (C) 2009-2017 Rocky Bernstein <rocky@gnu.org> |
| 2 | +# Copyright (C) 2009-2017, 2021 Rocky Bernstein <rocky@gnu.org> |
3 | 3 | # |
4 | 4 | # This program is free software: you can redistribute it and/or modify |
5 | 5 | # it under the terms of the GNU General Public License as published by |
|
16 | 16 | """Subsidiary routines used to "pack" and "unpack" TCP messages. """ |
17 | 17 |
|
18 | 18 | TCP_MAX_PACKET = 8192 # Largest size for a recv |
19 | | -LOG_MAX_MSG = 4 # int(log(TCP_MAX_PACKET) |
| 19 | +LOG_MAX_MSG = 4 # int(log(TCP_MAX_PACKET) |
20 | 20 |
|
21 | 21 |
|
22 | 22 | def pack_msg(msg): |
23 | | - fmt = '%%0%dd' % LOG_MAX_MSG # A funny way of writing: '%04d' |
24 | | - byte_msg = bytes(msg, 'UTF-8') |
25 | | - byte_fmt = bytes(fmt % len(byte_msg), 'UTF-8') |
| 23 | + fmt = "%%0%dd" % LOG_MAX_MSG # A funny way of writing: '%04d' |
| 24 | + byte_msg = bytes(msg, "UTF-8") |
| 25 | + byte_fmt = bytes(fmt % len(byte_msg), "UTF-8") |
26 | 26 | return byte_fmt + byte_msg |
27 | 27 |
|
| 28 | + |
28 | 29 | def unpack_msg(buf): |
29 | 30 | if len(buf) == 0: |
30 | 31 | # Fake a quit |
31 | | - return '', bytes('q'.encode('utf-8')) |
32 | | - length = int(buf[0:LOG_MAX_MSG]) |
33 | | - data = buf[LOG_MAX_MSG:LOG_MAX_MSG+length] |
34 | | - buf = buf[LOG_MAX_MSG+length:] |
| 32 | + return "", bytes("q".encode("utf-8")) |
| 33 | + length = int(buf[0:LOG_MAX_MSG]) |
| 34 | + data = buf[LOG_MAX_MSG : LOG_MAX_MSG + length] |
| 35 | + buf = buf[LOG_MAX_MSG + length :] |
35 | 36 | return buf, data |
36 | 37 |
|
| 38 | + |
37 | 39 | # Demo |
38 | | -if __name__=='__main__': |
39 | | - print(unpack_msg(pack_msg('Hello, there!'))[1]) |
| 40 | +if __name__ == "__main__": |
| 41 | + print(unpack_msg(pack_msg("Hello, there!"))[1]) |
40 | 42 | # assert unpack_msg(pack_msg(msg))[1] == msg |
41 | 43 | pass |
0 commit comments