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
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:
Content-Length header for HTTP) while setting a timeout (in case of network issues)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With