summaryrefslogtreecommitdiff
path: root/asciifarm/common/tcommunicate.py
diff options
context:
space:
mode:
authortroido <troido@hotmail.com>2017-12-31 00:10:14 +0100
committertroido <troido@hotmail.com>2017-12-31 00:10:14 +0100
commit38f3a3807373a19cacc0171dd7d5fd11f44dbd35 (patch)
tree9a411f192d5f6e565a7348988f18357ac39e8153 /asciifarm/common/tcommunicate.py
parent2170dc1bbfe845c2b5ae0a34d5608cd836627cec (diff)
merged roomedge into portal, moved tcommunicate and utils to common folder and fixed package when starting main directory
Diffstat (limited to 'asciifarm/common/tcommunicate.py')
-rw-r--r--asciifarm/common/tcommunicate.py32
1 files changed, 32 insertions, 0 deletions
diff --git a/asciifarm/common/tcommunicate.py b/asciifarm/common/tcommunicate.py
new file mode 100644
index 0000000..b1fc1b0
--- /dev/null
+++ b/asciifarm/common/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)
+