【问题标题】:Sending arbitrary data with Twisted使用 Twisted 发送任意数据
【发布时间】:2012-10-29 01:03:40
【问题描述】:

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

【问题讨论】:

    标签: python multithreading networking asynchronous twisted


    【解决方案1】:

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

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

    等等。

    【讨论】:

    • +1 谢谢。出于某种原因,我认为 reactor.listenUDP() 方法必须实例化侦听器对象。我不知道它可以提前完成。现在我可以做一个 network.send_stuff。
    猜你喜欢
    • 2013-12-22
    • 2015-04-08
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2011-05-04
    • 2014-04-11
    相关资源
    最近更新 更多