Skip to content

Instantly share code, notes, and snippets.

@KingCprey
Last active August 25, 2016 11:25
Show Gist options
  • Save KingCprey/1adac65d5dae5c1412a4383315a0ac68 to your computer and use it in GitHub Desktop.
Save KingCprey/1adac65d5dae5c1412a4383315a0ac68 to your computer and use it in GitHub Desktop.
Functions to transfer data
#u can change the length values to be sent as 64 bit integers instead of 32 bits, I wouldn't recommend doing so unless ur sending over 4GB of data in a single buffer (would not recommend cos mem errors)
def sendByte(sock,b):
if b>=256 or b<0:raise ValueError()
else:sock.send(struct.pack("!B",b))
def sendInt16(sock,s):sock.send(struct.pack("!h",s))
def sendUInt16(sock,s):sock.send(struct.pack("!H",s))
def sendInt32(sock,i):sock.send(struct.pack("!i",i))
def sendUInt32(sock,i):sock.send(struct.pack("!I",i))
def sendInt64(sock,l):sock.send(struct.pack("!l",l))
def sendUInt64(sock,l):sock.send(struct.pack("!L",l))
def sendString(sock,s):
sendUInt32(sock,len(s))
sock.send(s.encode("utf8"))
def sendBytes(sock,b,write_length=True):
if write_length:sendUInt32(sock,len(b))
sock.send(b)
def sendBoolean(sock,b):sendByte(sock,1 if b else 0)
def receiveBytes(sock,count=None,max_buffer=1024):
if not count:count=receiveUInt32(sock)
bytesleft=count
buffer=bytearray()
while bytesleft>0:
buff=sock.recv(max_buffer if bytesleft>max_buffer else bytesleft)
buffer=buffer+buff
bytesleft-=len(buff)
return buffer
def receiveByte(self,sock):return struct.unpack("!B",sock.recv(1))[0]
def receiveInt16(self,sock):return struct.unpack("!h",sock.recv(2))[0]
def receiveUInt16(self,sock):return struct.unpack("!H",sock.recv(2))[0]
def receiveInt32(self,sock):return struct.unpack("!i",sock.recv(4))[0]
def receiveUInt32(self,sock):return struct.unpack("!I",sock.recv(4))[0]
def receiveInt64(self,sock):return struct.unpack("!l",sock.recv(8))[0]
def receiveUInt64(self):return struct.unpack("!L",self.client_sock.recv(8))[0]
def receiveBoolean(self):return self.receiveByte()>0
def receiveString(self,strlen=None,encoding="utf8"):return self.client_sock.recv(self.receiveUInt32(sock) if not strlen else strlen).decode(encoding)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment