Advertisement
pmontp19

comms

Jun 5th, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.58 KB | None | 0 0
  1. import cPickle
  2. import socket
  3. import struct
  4.  
  5. marshall = cPickle.dumps
  6. unmarshall = cPickle.loads
  7.  
  8. def send(sock, *args):
  9.     buff = marshall(args)
  10.     value = socket.htonl(len(buff))
  11.     size = struct.pack("L",value)
  12.     sock.send(size)
  13.     sock.send(buff)
  14.  
  15.  
  16. def receive(sock):
  17.     size = struct.calcsize("L")
  18.     size = sock.recv(size)
  19.     try:
  20.         size = socket.ntohl(struct.unpack("L", size)[0])
  21.     except struct.error, e:
  22.         return ''
  23.  
  24.     buff = ""
  25.  
  26.     while len(buff) < size:
  27.         buff = sock.recv(size - len(buff))
  28.  
  29.     return unmarshall(buff)[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement