Python SetTimeout 永久打印



我有下一个不良行为:

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"

在这里,我有回显服务器,其超时由设置超时(5.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

相关内容

  • 没有找到相关文章

最新更新