1 def send(socket, message):
2 """Send message via socket, encoded and delimited the way recv() expects.
4 In detail, all \ and $ in message are escaped with prefixed \, and an
5 unescaped $ is appended as a message delimiter. Then, socket.send() is
6 called as often as necessary to ensure message is sent fully, as
7 socket.send() due to buffering may not send all of it right away.
9 Assuming socket is blocking, it's rather improbable that socket.send() will
10 be partial / return a positive value less than the (byte) length of msg –
11 but not entirely out of the question. See:
12 - <http://stackoverflow.com/q/19697218>
13 - <http://stackoverflow.com/q/2618736>
14 - <http://stackoverflow.com/q/8900474>
16 This also handles a socket.send() return value of 0, which might be
17 possible or not (?) for blocking sockets:
18 - <http://stackoverflow.com/q/34919846>
22 if char in ('\\', '$'):
23 escaped_message += '\\'
24 escaped_message += char
25 escaped_message += '$'
26 data = escaped_message.encode()
28 while totalsent < len(data):
29 sent = socket.send(data[totalsent:])
31 raise RuntimeError('socket connection broken')
32 totalsent = totalsent + sent
36 """Get full send()-prepared message from socket.
38 In detail, socket.recv() is looped over for sequences of bytes that can be
39 decoded as a Unicode string delimited by an unescaped $, with \ and $
40 escapable by \. If a sequence of characters that ends in an unescaped $
41 cannot be decoded as Unicode, None is returned as its representation. Stop
42 once socket.recv() returns nothing.
44 Under the hood, the TCP stack receives packets that construct the input
45 payload in an internal buffer; socket.recv(BUFSIZE) pops up to BUFSIZE
46 bytes from that buffer, without knowledge either about the input's
47 segmentation into packets, or whether the input is segmented in any other
48 meaningful way; that's why we do our own message segmentation with $ as a
56 data += socket.recv(1024)
70 except UnicodeDecodeError: