I am trying to create an sockets client and server and exchange data between them. I have the code below, but it is unreliable. It works on the LAN, but once I test it on older computers over the internet, I get errors because one of the side misreads a piece of chunk as chunk length. I added sendall("1")
to acknowledge that the chunk has been received, but it did not solve it. I also tried increasing time.sleep
to 1 second, and decreased the chunk length down to 4096
and 512
bits. Any help is appreciated. The whole code is here, altered: https://github.com/hclivess/Bismuth/blob/master/node.py
Server code:
receive_left = self.request.recv(10)
while int(receive_left) > 0: # while there are chunks to receive
chunk_length = self.request.recv(10) # identify chunk length
app_log.info("Node: Received chunk length: " + str(chunk_length))
self.request.sendall("1") # acknowledge chunk length
time.sleep(0.1)
chunk = self.request.recv(int(chunk_length))
app_log.info("Node: Received chunk: " + chunk)
chunks = chunks + str(chunk)
receive_left = int(receive_left) - 1
app_log.info("Node: Combined chunks: " + chunks)
Client code:
chunks = 0
while int(receive_left) > 0:
chunk_length = len(data_split[chunks])
while len(str(chunk_length)) != 10:
chunk_length = "0" + str(chunk_length)
app_log.info("Node: chunk length to dispatch: " + str(chunk_length))
self.request.sendall(
chunk_length) # send how much they should receive
time.sleep(0.1)
self.request.recv(1) # receive chunk length acknowledgement
app_log.info("Node: chunk to dispatch: " + str(data_split[chunks])) # send chunk
self.request.sendall(data_split[chunks]) # send chunk
time.sleep(0.1)
receive_left = int(receive_left) - 1
chunks = chunks + 1