1

我在 python 中制作了一个简单的网络服务器,之前遇到了一些问题,如下所述:Python (3.3) Webserver script with an interesting error

在那个问题中,答案是使用While True:循环,以便立即解决任何崩溃或错误,因为它会重新启动。

我已经使用了一段时间,仍然想让服务器每隔几分钟自动重启一次,但是在 Linux 上由于某种原因它对我不起作用。在 Windows 上,下面的代码工作正常,但在 linux 上它一直说

Handler class up here
...
...
class Server:

    def __init__(self):

        self.server_class = HTTPServer
        self.server_adress = ('MY IP GOES HERE, or localhost', 8080)
        global httpd
        httpd = self.server_class(self.server_adress, Handler)
        self.main()

    def main(self):

        if count > 1:

            global SERVER_UP_SINCE
            HOUR_CHECK = int(((count - 1) * RESTART_INTERVAL) / 60)

            SERVER_UPTIME = str(HOUR_CHECK) + " MINUTES"


            if HOUR_CHECK > 60:
                minutes = int(HOUR_CHECK % 60)
                hours = int(HOUR_CHECK // 60)
                SERVER_UPTIME = ("%s HOURS, %s MINUTES" % (str(hours), str(minutes)))

            SERVING_ON_ADDR = self.server_adress
            SERVER_UP_SINCE = str(SERVER_UP_SINCE)
            SERVER_RESTART_NUMBER = count - 1        

            print("""
SERVER INFO
-------------------------------------
SERVER_UPTIME: %s
SERVER_UP_SINCE: %s
TOTAL_FILES_SERVED: %d
SERVING_ON_ADDR: %s
SERVER_RESTART_NUMBER: %s
\n\nSERVER HAS RESTARTED
            """ % (SERVER_UPTIME, SERVER_UP_SINCE, TOTAL_FILES, SERVING_ON_ADDR, SERVER_RESTART_NUMBER))

        else:

            print("SERVER_BOOT=1\nSERVER_ONLINE=TRUE\nRESTART_LOOP=TRUE\nSERVING_ON_ADDR:%s" % str(self.server_adress))

        while True:

            try:

                httpd.serve_forever()

            except KeyboardInterrupt:

                print("Shutting down...")
                break
                httpd.shutdown()
                httpd.socket.close()
                raise(SystemExit)

        return


def server_restart():
    """If you want the restart timer to be longer, replace the number after the RESTART_INTERVAL variable"""

    global RESTART_INTERVAL
    RESTART_INTERVAL = 10
    threading.Timer(RESTART_INTERVAL, server_restart).start()
    global count
    count = count + 1
    instance = Server()


if __name__ == "__main__":

    global SERVER_UP_SINCE
    SERVER_UP_SINCE = strftime("%d-%m-%Y %H:%M:%S", gmtime())
    server_restart()

基本上,我创建一个线程每 10 秒重新启动一次(出于测试目的)并启动服务器。十秒钟后它会说

  File "/home/username/Desktop/Webserver/server.py", line 199, in __init__
    httpd = self.server_class(self.server_adress, Handler)
  File "/usr/lib/python3.3/socketserver.py", line 430, in __init__
    self.server_bind()
  File "/usr/lib/python3.3/http/server.py", line 135, in server_bind
    socketserver.TCPServer.server_bind(self)
  File "/usr/lib/python3.3/socketserver.py", line 441, in server_bind
    self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use

正如您在该except KeyboardInterruption行中看到的,我尝试了一切使服务器停止,程序停止,但它不会停止。但我真正想知道的是如何让这个服务器能够重新启动,而不会出现一些奇怪的错误。

4

0 回答 0