0

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
HCLivess
  • 1,015
  • 1
  • 13
  • 21
  • 1
    FYI, see http://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string for a better way to add zero padding to a number. – Barmar Dec 08 '16 at 09:03
  • 1
    The length in `recv()` is a maximum amount to read, but it can read less than that. You need to call `recv()` in a loop until you get all the bytes you want. – Barmar Dec 08 '16 at 09:05
  • Thanks, Barmar. This is probably the answer. – HCLivess Dec 08 '16 at 09:09
  • You could do what Barmar said and also add some error detecting like CRC in your header to verify if the received data is not corrupted. – Victor Sanchez Dec 08 '16 at 09:16

0 Answers0