3

While im trying to recv data with a while loop the loop not stopping even when there is no data

import socket


class Connect:
    connect = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def __init__(self, server_ip, server_port):
        self.connect.connect((server_ip, server_port))

    def recv(self):
        data_ls = []
        while True:
            data = self.connect.recv(2048)
            if not data: # after getting the first data
                break #    Python wont come to this "if" so it wont break!

            data = data.decode('utf-8')
            data_ls.append(data)
        return data_ls
3
  • 1
    What is the protocol supposed to be here? The only time there's no more data is when the other side has closed (or at least half-shutdown) the socket. Do you want to read until the client does that, or just until you've drained the current buffer, or…? Commented Jul 13, 2018 at 1:14
  • some custom port 25569 and there is a server on the other side Commented Jul 13, 2018 at 12:13
  • 1
    That doesn’t answer what the protocol is supposed to be. And meanwhile, it doesn’t matter whether the other side is a client or a server, it’s still the same question: are you trying to read until the server closes or at least half-shutdowns the connection, or until there’s a momentary lull in traffic, or what? Commented Jul 13, 2018 at 16:29

1 Answer 1

5

Because socket.recv is a blocking call. This means that your program will be paused until it receives data.

You can set a time limit on how long to wait for data:

socket.settimeout(seconds_to_wait_for_data)

Or, you can make the socket not block:

sock.setblocking(False)

Note that under your current implementation, your code will probably busy wait for data to be available, potentially using more system resources than necessary. You can prevent this by:

  • looking for a signal for when there isn't any more data from the server at the start (such as a Content-Length header for HTTP) while setting a timeout (in case of network issues)
  • using a library implementing a higher level protocol
Sign up to request clarification or add additional context in comments.

1 Comment

"This means that your program will be paused until the amount of data you asked for (2048 bytes) is available to receive." That's not true. It will block until any data is available to receive. Even if it's just one byte, it will receive that one byte and return it to you.

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.