python3 套接字读取,避免 while True 或最佳实践

python3 socket reading, avoid while True or best practice

我必须在 python 中编写一个简单的 tcp 转发器,它将永远 运行。我将以 1 分钟的间隔获取数据。那么我是否必须 运行 while true 中的 socket.read()? 有没有更好的方法来避免所有那些不必要的 cpu 循环? 还有一件事,socket.read() 在线程中。

归根结底,您仍然需要一些 while True。通常的做法是在某个地方睡觉。

如果需要从多个套接字读取,则需要使用select函数。 https://docs.python.org/3/library/select.html。这是因为read()操作可能会阻塞。

do I have to run the socket.read() in while true? Is there any better way to avoid all those unnecessary cpu-cycles?

阻塞read()。因此,您的进程(线程)在等待下一次网络通信时实质上是在休眠,而不是消耗 CPU 个周期。