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