This code is meant to send an object (any object) over a connection to a recieving program. I want to make sure that i haven't made any red flags. It seems to work fine, i've sent tuples with data (bools, strings and lists with other lists) and it gets recieved fine.
import pickle
packetsize = 4096
def send_msg(conn, data):
try:
msg = pickle.dumps(data)
print("calcing packetcount")
packetcount = str(int(len(msg)/(packetsize))+1)
if (len(msg)%packetsize) == 0: packetcount -= 1
while len(packetcount) != 8:
packetcount = "0" + packetcount
print("sending packetcount: " + packetcount)
conn.sendall(packetcount.encode())
print("sending message")
conn.sendall(msg)
print("sent message")
return True
except:
return False
def recv_msg(conn):
# Read message length and unpack it into an integer
print("waiting for message")
messagesize = int(conn.recv(8).decode())
print("got message size: {} packets".format(str(messagesize)))
print("recieving message")
data = []
for _ in range(messagesize):
print("recieving packet")
packet = conn.recv(packetsize)
print("recieved packet: {}".format(packet))
if not packet: break
data.append(packet)
# Read the message data
print("got ALL PACKETS")
return pickle.loads(b"".join(data))