Skip to content Skip to sidebar Skip to footer

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.SO

Solution 1:

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

Post a Comment for "Python Socket Recv Data In While Loop Not Stopping"