【问题标题】:Getting Twisted to work in the background让 Twisted 在后台工作
【发布时间】:2025-12-30 19:35:07
【问题描述】:

您好,我是 Twisted 的新手,我想将它用作我的客户端/服务器升级。

我有一个做一些单元测试的软件,我想添加 Twisted。

有 2 台计算机 1 用于控制测试(客户端)和 1 用于测试特定单元(服务器)

对于服务器部分,使用twisted 没有问题。因为当激活反应器时,服务器正在监听并等待来自客户端的请求。

在客户端部分我有一些问题。

盯着客户端时

reactor.run()

软件进入事件驱动模式并等待事件...(连接,发送...) 问题是我想做很多事情,而不仅仅是看我的交流。

假设我有一个功能:

电压 = self.UnitTest.GetVoltage()

如果电压.......

当前 = self.UnitTest.GetCurrent()

如果当前.....

我希望 UnitTest 方法将他们的请求发送到扭曲的客户端,这可能吗?

【问题讨论】:

    标签: python sockets networking client-server twisted


    【解决方案1】:

    如果是用于测试,请查看文档:unit test with trial

    要编写测试,您可以使用经典的回调方式:

    from twisted.internet import defer
    
    class SomeWarningsTests(TestCase):
        def setUp(self):
            #init your connection , return the deferred that callback when is ready
        def tearDown(self):
            # disconnect from the server
        def getVoltage(self):
            #connect to you serveur and get the voltage , so return deferred
        def test_voltage(self):
            def testingVoltage(result):
                 if not result:
                      raise Exception("this not normal")
                 return result
            return self.getVoltage.addCallback(testingVoltage)
    
        #other way
        def getCurrent(self):
            #connect to you serveur and get the current(?) , so return deferred
    
        @defer.inlineCallbacks
        def test_current(self):
            current = yield self.getCurrent()
            if not current:
                raise  Exception("this not normal")
            defer.returnValue(current)
    

    【讨论】: