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

1 投票
1 回答
1839 浏览
提问于 2025-04-17 07:56

我的客户端(基于twisted框架)应该在连接丢失时自动重新连接到服务器,我需要测试这个功能。这里是我的测试方法,@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 个回答

2

你的服务器仍然在运行(从你问题中的代码来看是这样的)。关闭一个与客户端的连接并不会阻止服务器接受新的连接。

如果你想让一个监听的端口停止监听,可以使用 port.stopListening() (注意它会返回一个 Deferred 对象)。你可以通过再次调用 reactor.listenTCP(或者你最开始用来开始监听的其他API)来重新开始监听这个端口。

撰写回答