This is essentially a frequently asked question. How do I make a conclusion on one output connection result by another?
The UDP ↔ TCP specifications in this question do not violate the general answer specified in the FAQ section. Just notice that DatagramProtocol easier to work with than Protocol , because you already have an instance of DatagramProtocol without having to interact with the factory, as with Protocol .
Put another way:
from twisted.internet.protocol import Protocol, Factory, DatagramProtocol from twisted.internet import reactor class TCPServer(Protocol): def connectionMade(self): self.port = reactor.listenUDP(8000, UDPServer(self)) def connectionLost(self, reason): self.port.stopListening() class UDPServer(DatagramProtocol): def __init__(self, stream): self.stream = stream def datagramReceived(self, datagram, address): self.stream.transport.write(datagram) def main(): f = Factory() f.protocol = TCPServer reactor.listenTCP(8000, f) reactor.run() if __name__ == '__main__': main()
Note the significant change: UDPServer needs to call the method on the TCPServer instance TCPServer that it TCPServer reference to that instance. This is achieved by the fact that the TCPServer instance passes itself to the UDPServer initializer, and the UDPServer initializer saves this link as an attribute of the UDPServer instance.
source share