使用Twisted发送任意数据

时间:2012-10-29 01:03:40

标签: python multithreading networking asynchronous twisted

我的代码示例如下。我想在程序的各个点上任意发送数据。扭曲似乎很适合倾听然后做出反应,但我如何简单地发送数据。

    from twisted.internet.protocol import DatagramProtocol
    from twisted.internet import reactor
    import os

    class listener(DatagramProtocol):

        def __init__(self):

        def datagramReceived(self, data, (host, port)):
            print "GOT " + data

        def send_stuff(data):
            self.transport.write(data, (host, port))

    reactor.listenUDP(10000, listener())
    reactor.run()

    ##Some things happen in the program independent of the connection state
    ##Now how to I access send_stuff

1 个答案:

答案 0 :(得分:3)

您的示例已包含一些发送数据的代码:

    def send_stuff(data):
        self.transport.write(data, (host, port))

换句话说,你的问题的答案是“call send_stuff”甚至“call tr​​ansport.write”。

在评论中你问:

#Now how to I access send_stuff

当您使用Twisted时,如何“访问”对象或方法并没有什么特别之处。它与您可能编写的任何其他Python程序相同。使用变量,属性,容器,函数参数或任何其他工具来维护引用到对象。

以下是一些例子:

# Save the listener instance in a local variable
network = listener()
reactor.listenUDP(10000, network)

# Use the local variable to connect a GUI event to the network
MyGUIApplication().connect_button("send_button", network.send_stuff)

# Use the local variable to implement a signal handler that sends data
def report_signal(*ignored):
    reactor.callFromThread(network.send_stuff, "got sigint")
signal.signal(signal.SIGINT, report_signal)

# Pass the object referenced by the local variable to the initializer of another
# network-related object so it can save the reference and later call methods on it
# when it gets events it wants to respond to.
reactor.listenUDP(20000, AnotherDatagramProtocol(network))

等等。