开发者

Python: Stop the socket-receiving-process

开发者 https://www.devze.com 2023-03-04 21:51 出处:网络
I receive data from some device via socket-module. But after some time the device stops sending packages.

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 pa开发者_如何学Pythonrt of the solution. See also: How to set timeout on python's socket recv method?


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.


while 1:
    data = conn.recv(4)
    if not data: break
    f.write(data)

Also, example in python docs

0

精彩评论

暂无评论...
验证码 换一张
取 消