2

I receive data from some device via socket-module. But after some time the device stops sending packages. Then I want to interupt the for-loop. While True doesn't work, because he receives more then 100 packages. How can I stop this process? s stands for socket.

...
for i in range(packages100):
    data = s.recv(4)
    f.write(data)
...

Edit: I think socket.settimeout() is part of the solution. See also: How to set timeout on python's socket recv method?

Community
  • 1
  • 1
kame
  • 20,848
  • 33
  • 104
  • 159

2 Answers2

3

If your peer really just stops sending data, as opposed to closing the connection, this is tricky and you'll be forced to resort to asynchronous reading from this socket.

Put it in asynchronous mode (the docs and Google are your friends), and try to read it each time, instead of the blocking read. You can then just stop "trying" anytime you wish. Note that by nature of async IO your code will be a bit different - you will no longer be able to assume that once recv returns, it actually read some data.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
2
while 1:
    data = conn.recv(4)
    if not data: break
    f.write(data)

Also, example in python docs

bpgergo
  • 15,669
  • 5
  • 44
  • 68