diff options
| author | Wango Fett <wangofett@tilde.town> | 2017-10-26 17:05:49 +0000 |
|---|---|---|
| committer | Wango Fett <wangofett@tilde.town> | 2017-10-26 17:05:49 +0000 |
| commit | 3a8afeb369d4ef66c9b991e64febe66a35338177 (patch) | |
| tree | 460a2b88f6d5de2258ad17a319a4672afcde434d /asciifarm/client/tcommunicate.py | |
Pip installable!
Diffstat (limited to 'asciifarm/client/tcommunicate.py')
| -rw-r--r-- | asciifarm/client/tcommunicate.py | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/asciifarm/client/tcommunicate.py b/asciifarm/client/tcommunicate.py new file mode 100644 index 0000000..b1fc1b0 --- /dev/null +++ b/asciifarm/client/tcommunicate.py @@ -0,0 +1,32 @@ + +HEADER_SIZE = 4 + + +# this module is for sending discree messages over TCP +# this is achieved by prefixing all messages with their length +# calls to send and recv will also keep attempting to send all data unless this proves impossible + + +def send(sock, msg): + length = len(msg) + header = length.to_bytes(4, byteorder="big") + totalmsg = header + msg + sock.sendall(totalmsg) + +def receive(sock): + header = recvall(sock, 4) #sock.recv(4) + length = int.from_bytes(header, byteorder="big") + return recvall(sock, length) + +def recvall(sock, length): + chunks = [] + bytes_recd = 0 + while bytes_recd < length: + chunk = sock.recv(min(length - bytes_recd, 4096)) + if chunk == b'': + break + #raise RuntimeError("socket connection broken") + chunks.append(chunk) + bytes_recd = bytes_recd + len(chunk) + return b''.join(chunks) + |
