1

I want to get out of loop when there is no data but loop seems to be stopping at recvfrom

image=''
while 1:
        data,address=self.socket.recvfrom(512)
        if data is None:break
        image=image+data
        count=count+1
        print str(count)+' packets received...'
2
  • What do you mean by stopping? Does the program crash or does it hang? Commented Sep 21, 2009 at 17:10
  • Have you set the socket to non-blocking mode? Commented Sep 21, 2009 at 17:11

4 Answers 4

4

Try setting to a non-blocking socket. You would do this before the loop starts. You can also try a socket with a timeout.

Sign up to request clarification or add additional context in comments.

Comments

2

recvfrom may indeed stop (waiting for data) unless you've set your socket to non-blocking or timeout mode. Moreover, if the socket gets closed by your counterpart, the indication of "socket was closed, nothing more to receive" is not a value of None for data -- it's an empty string, ''. So you could change your test to if not data: break for more generality.

Comments

0

What is the blocking mode of your socket?

If you are in blocking mode (which I think is the default), your program would stop until data is available... You would then not get to the next line after the recv() until data is coming.

If you switch to non-blocking mode, however (see socket.setblocking(flag)), I think that it will raise an exception you would have to catch rather than null-check.

Comments

0

You might want to set socket.setdefaulttimeout(n) to get out of the loop if no data is returned after specified time period.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.