我有一个 QA 系统,它运行测试阶段并使用类描述的不同功能,其中一个类通过打开 TCP 服务器并等待客户端连接来提供 TCP 服务。
main 函数在系统启动时运行这个套接字类。 并在启动后负责等待客户端连接。
但是,'accept' 函数在运行时会消耗大量 CPU 25%>
我在网上搜索了一个解决方案,但是没有在线程内<=运行TCP服务器的例子。 (仅用于创建每个客户端的线程,这是显而易见的)。
能否请您指点我做这件事的好方法,或者告诉我我做错了什么。
…
_thread.start_new_thread( self.Server_wait_to_clients_thread,())
…
def Server_wait_to_clients_thread(self):
try:
print("Server started")
threading.current_thread().name = "TCPServer"
try:
self.Server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.Server.bind(('0.0.0.0', self.Port))
self.Server.listen()
while 1:
(clientsocket, address) = self.Server.accept() #<----------------------(taking a lot of CPU)
print(" Connected! " +str(unitNew.address))
create_recieveThread()
except Exception as ex:
raise ex
finally:
print("Server - stoped ")
self.Server.close()
except Exception as ex:
raise ex