Infinite loop when decoding a message received from a Socket in Python 3.3.5

1.8k Views Asked by At

I'm using this line of code to decode the received string from a Socket in Python but when I run the program, this line runs infinitely and just shows up as a blinking cursor in the Python shell:

received = self.sock.recv(16).decode()

If you know how to fix it, any help would be appreciated!

1

There are 1 best solutions below

0
On

It is not in an infinite loop. It is just blocking on the recv call, because there is not enough data to read. You have requested to read 16 bytes, and recv will block until 16 bytes are available - and your socket doesn't have 16 bytes yet.

Try with a lower value - or even better - make the socket non-blocking. Writing non-blocking socket reads is a little more work - so if you know exactly how many bytes to read, it is better to give the exact number to read() instead.

If not, take a look at this answer on non-blocking sockets. The answers have two different approaches.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?