我有下一个不良行为:
def run(self):
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._socket.bind(("0.0.0.0", self.port()))
self._socket.listen(5)
self._socket.settimeout(5.0)
while not self.finish.isSet():
try:
conn, addr = self._socket.accept()
c = connection(conn, addr)
self.activeconn.append(c)
c.start()
print "New session from address {}".format(addr)
except Exception as e:
print e
self.activeconn = self.child_list()
self._socket.close()
print "Server is closing..."
for conn in self.activeconn:
conn.join()
time.sleep(4)
print "Server is closed"
这里我有一个由settimeout(5.0)设置超时的echo服务器。问题是我的控制台每次超时都会打印“超时”。我可以以某种方式关闭它吗?
答案 0 :(得分:0)
每当在套接字上执行操作期间发生超时时,都会引发socket.timeout
异常。在您的代码中,您正在捕获该异常并将其打印出来:
try:
conn, addr = self._socket.accept()
# ...
except Exception as e:
print e
如果你想防止"超时"出现在输出中的行,只是捕获异常并禁止它:
try:
conn, addr = self._socket.accept()
# ...
except socket.error:
pass
except Exception as e:
print e