-1

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!

Novaroid
  • 1
  • 1
  • This is not really enough code to spot any problems. Also, use proper code formatting. – deets Jun 17 '15 at 14:09
  • 1
    Have you tried to send any data from the server that it is connected to or they both just sitting there? – Dan Jun 20 '15 at 00:09

1 Answers1

1

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?

Community
  • 1
  • 1
kjp
  • 3,086
  • 22
  • 30