0

I am Using Python socket lib, i want to receive the entire data coming from server i have tried using loops but it stucking after reading the data.

    def readReply(self):
        recv_data = b''
        while True:
            data = self.client_socket.recv(1024)
            if data:
                recv_data += data
            else:
                break
        return recv_data
8
  • You're collecting the data in a variable named recv_data, but then you return a different variable named buffer. Commented Aug 29, 2022 at 2:51
  • sorry that's a typo error same Commented Aug 29, 2022 at 3:03
  • What does "but it stucking after reading the data" mean? Commented Aug 29, 2022 at 3:03
  • data condition is never getting false then what will happen Commented Aug 29, 2022 at 3:09
  • @Jocefyneroot is that really the problem? Aren't you stuck on self.client_socket.recv(1024)? If the socket is in blocking mode and no data is received, this function will block the thread forever. Setting a timeout before receiving any data and using a try-except block to catch the timeout exception should be the way to go. Commented Aug 29, 2022 at 3:15

1 Answer 1

1

What I mean about the timeout is this:

def readReply(self):
    recv_data = b''

    # This will block the socket for 0.1s
    #
    # If you have a poor internet connection, you
    # may need to increase this value to a higher
    # one.
    self.client_socket.settimeout(0.1)
    while True:
        try:
            data = self.client_socket.recv(1024)
        except:
            break
        else:
            recv_data += data

    return recv_data

Once the timeout is reached, the while-loop will break. Note: if you don't want to freeze the main thread while waiting for the incoming data (in case you're using a GUI), you should use multithreading.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.