2

我的代码示例如下。我想在程序的各个点任意发送数据。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
4

1 回答 1

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))

等等。

于 2012-10-29T15:39:58.197 回答