Python 使用Twisted发送任意数据

Python 使用Twisted发送任意数据,python,multithreading,networking,asynchronous,twisted,Python,Multithreading,Networking,Asynchronous,Twisted,下面是我的代码示例。我想在程序的各个点任意发送数据。Twisted似乎非常适合于倾听然后做出反应,但如何简单地发送数据 from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import os class listener(DatagramProtocol): def __init__(self):

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

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

    def send_stuff(data):
        self.transport.write(data, (host, port))
换句话说,你的问题的答案是“呼叫发送东西”,甚至是“呼叫传输。写”

你在评论中问:

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

等等。

+1谢谢。出于某种原因,我认为reactor.listenUDP()方法必须实例化侦听器对象。我不知道这可以事先做。现在我可以做一个网络。发送你的东西。