Twisted UDP to TCP Bridge

I recently made the first hit in Twisted / Python by creating an application that echoes incoming UDP strings from a TCP port. I suggested that it would be very simple, but I could not get it to work. The code below is an example of TCP and UDP Server, modified for collaboration. I'm just trying to pass some data between them. Any help would be appreciated.

from twisted.internet.protocol import Protocol, Factory, DatagramProtocol from twisted.internet import reactor class TCPServer(Protocol): def dataReceived(self, data): self.transport.write(data) class UDPServer(DatagramProtocol): def datagramReceived(self, datagram, address): #This is where I would like the TCPServer dataReceived method run passing "datagram". I've tried: TCPServer.dataReceived(datagram) #But of course that is not the correct call because UDPServer doesn't recognize "dataReceived" def main(): f = Factory() f.protocol = TCPServer reactor.listenTCP(8000, f) reactor.listenUDP(8000, UDPServer()) reactor.run() if __name__ == '__main__': main() 
0
source share
1 answer

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.

+2
source

All Articles