views:

147

answers:

4

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...'
A: 

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.

Uri
+4  A: 

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

David Berger
A: 

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

half.italian
+2  A: 

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.

Alex Martelli