Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python socket recv data in while loop not stopping

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
like image 982
dsal3389 Avatar asked Sep 09 '26 13:09

dsal3389


1 Answers

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
like image 142
noɥʇʎԀʎzɐɹƆ Avatar answered Sep 11 '26 03:09

noɥʇʎԀʎzɐɹƆ