重新启动与python socketserver的连接

时间:2016-02-26 21:37:09

标签: python python-3.x socketserver

我正在使用Python 3 socketserver创建服务器,并且在尝试重新启动连接时遇到问题。我希望能够关闭它,从文件中读取配置并重新开始,但是,我遇到了Address already in use OSError。我认为使用server_close()方法它会清除自己(如doc中所指定的那样),这样我就可以重新开始,但我不是。

这是我的代码:

class NetworkCommunicationService(Services):
    def __init__(self):
        self.__connection__ = None
        self.__setup__()

    def __setup__(self):
        host, port = get_setup()
        self.__connection__ = ConnectionHandler.setup_connection_handler(host, port)

    def service_entry_point(self):
        try:
            self.__connect__()
        except FileNotFoundError:
            Output.config_error()
        finally:
            self.__connection__.shutdown()

    def __connect__(self):
            self.__connection__.serve_forever()

    def terminate(self):
        self.__connection__.shutdown()
        self.__connection__.server_close()

    def reset(self):
        self.terminate()
        self.__setup__()
        self.service_entry_point()

handle()中调用的serve_forever()方法取自我现在不记得的某个网站。我最后只添加了close(),希望它有所帮助。

def handle(self):
    # self.request is the TCP socket connected to the client
    self.data = self.request.recv(1024)
    print("{} wrote:".format(self.client_address[0]))
    print(self.data)
    # just send back the same data, but upper-cased
    self.request.sendall(self.data.upper())
    self.request.close()

我该怎么做才能重置连接?

0 个答案:

没有答案