Python:停止套接字接收进程
我通过套接字模块从某些设备接收数据。 但一段时间后,设备停止发送包。 然后我想中断 for 循环。 而True不行,因为他收到了100多个包裹。 我怎样才能停止这个过程? s 代表插座。
...
for i in range(packages100):
data = s.recv(4)
f.write(data)
...
编辑: 我认为 socket.settimeout() 是解决方案的一部分。参见: 如何在python的套接字recv方法上设置超时?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的对等方确实只是停止发送数据,而不是关闭连接,那么这很棘手,您将被迫从此套接字进行异步读取。
将其置于异步模式(文档和 Google 是你的朋友),并尝试每次都读取它,而不是阻塞读取。然后,您可以随时停止“尝试”。请注意,根据异步 IO 的性质,您的代码会有所不同 - 您将不再能够假设一旦
recv
返回,它实际上会读取一些数据。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.另外,Python 文档中的示例
Also, example in python docs