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
dsal3389
  • 658
  • 1
  • 7
  • 26
  • 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…? – abarnert Jul 13 '18 at 01:14
  • some custom port 25569 and there is a server on the other side – dsal3389 Jul 13 '18 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? – abarnert Jul 13 '18 at 16:29

1 Answers1

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
Leif Gruenwoldt
  • 13,561
  • 5
  • 60
  • 64
noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67
  • 5
    "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. – abarnert Jul 13 '18 at 01:12