如何在Python中关闭并启动服务器Twisted?

时间:2011-12-07 23:13:57

标签: python twisted trial

我的客户端(基于扭曲)应该在连接丢失时自动重新连接到服务器,我需要对此功能进行测试,这是我的测试方法,其中@todo注释非常清楚预期的行为:

@defer.inlineCallbacks
def test_reconnect_on_connection_loss(self):
    client = SMPPClientFactory(self.config)
    client.reConnect = mock.Mock(wraps=client.reConnect)
    # Connect
    smpp = yield client.connect()

    # Bind
    yield smpp.bindAsTransmitter()

    # @todo: A connection loss is expected here
    #        the client is supposed to try reconnections
    #        for a while, the server then shall start
    #        again and the client will get connected.

    # Unbind & Disconnect
    yield smpp.unbindAndDisconnect()

    ##############
    # Assertions :
    # Protocol verification
    self.assertNotEqual(0, client.reConnect.call_count)

在服务器端,我在收到bindAsTransmitter请求后尝试中止连接:

class LooseConnectionOnBindSMSC(SMSC):

    def handleBindAsTransmitter(self, reqPDU):
        self.sendSuccessResponse(reqPDU)

        # Connection is aborted here:
        self.transport.abortConnection()

连接成功中止,我的客户端开始尝试按预期重新连接,但它永远不会让我的服务器再次启动。

1 个答案:

答案 0 :(得分:1)

您的服务器仍在运行(据您所知,代码中的代码可以告诉您)。关闭与客户端的一个连接不会阻止服务器接受新连接。

停止侦听侦听端口的方法是使用port.stopListening()(请注意,它会返回Deferred)。您可以使用另一个reactor.listenTCP(或您第一次开始收听的任何API)呼叫再次开始侦听端口。