Search code examples
pythonmultithreadingnetwork-programmingasynchronoustwisted

Sending arbitrary data with Twisted


An example of my code is as follows. I would like to arbitrarly send data at various points in the program. Twisted seems great for listening and then reacting, but how to I simply send data.

    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

Solution

  • Your example already includes some code that sends data:

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

    In other words, the answer to your question is "call send_stuff" or even "call transport.write".

    In a comment you asked:

    #Now how to I access send_stuff
    

    There's nothing special about how you "access" objects or methods when you're using Twisted. It's the same as in any other Python program you might write. Use variables, attributes, containers, function arguments, or any of the other facilities to maintaining references to objects.

    Here are some examples:

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

    And so on.