如何在python中使用reactor链接函数?

时间:2014-05-20 12:27:01

标签: python-2.7 twisted deferred chaining

我的代码:

class Server(DatagramProtocol):

    SSDP_ADDR = "239.255.255.250"
    SSDP_PORT = 1900
    MS = "M-SEARCH * HTTP/1.1\r\nHOST: {}:{}\r\nMAN: 'ssdp:discover'\r\nMX: 2\r\nST: ssdp:all\r\n\r\n".format(SSDP_ADDR, SSDP_PORT)

    def __init__(self, iface):
        self.iface = iface
        self.Thread = None
        self.Thread = threading.Thread(target=self.startReactor)
        self.Thread.setDaemon(True)
        self.scanThread.start()

    def startReactor(self):
        """
        """
        reactor.callFromThread(self.sendMsearch)
        if reactor.callWhenRunning(lambda: None) is not None:
            reactor.run(installSignalHandlers=0)

    def sendMsearch(self):
        """ Sending M-SEARCH message
        """
        d = defer.Deferred()
        port = reactor.listenUDP(0, self, interface=self.iface)
        port.write(Server.MS, (Server.SSDP_ADDR, Server.SSDP_PORT))
        d = reactor.callLater(2.5, port.stopListening) # MX + a wait margin
        d.addCallback(self.cleanUp)

    def cleanUp(self, x):
        """
        """
        # stop thread and cleanup

    def datagramReceived(self, datagram, (host, port)):
        # doing some work

在上面的代码中,我必须在完成port.stopListening后调用cleanUp()。

还有我如何杀死这个帖子

这里有链接吗?

如果没有,那么如何实现我的目标。

1 个答案:

答案 0 :(得分:2)

在此示例中,对于线程使用反应器是完全错误的。只有在调用reactor.run的同一个线程中调用Twisted API才是安全的。

在您的示例中,startReactorsendMsearch在不同的线程中被调用。前者调用reactor.run,后者调用其他Twisted API。

如果您想将Twisted与其他阻止Python代码集成,您可能需要查看https://pypi.python.org/pypi/crochet