Twisted UDP to TCP Bridge [英] Twisted UDP to TCP Bridge
问题描述
最近我第一次尝试使用 Twisted/Python 构建一个应用程序,该应用程序将传入的 UDP 字符串从 TCP 端口中回显.我认为这将非常简单,但我无法让它发挥作用.下面的代码是示例 TCP &UDP Server 修改为一起运行.我只是想在两者之间传递一些数据.任何帮助将不胜感激.
Recently I've taken my first stab at Twisted/Python building an app that echoes incoming UDP strings out the TCP port. I assumed this would be very simple, but I haven't been able to get it to work. The code below is the example TCP & UDP Server modified to run together. I'm just trying to pass some data between the two. 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's 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()
推荐答案
这基本上是常见问题 如何使一个连接上的输入导致另一个连接上的输出?
此问题中的 UDP<->TCP 细节不会破坏常见问题解答条目中给出的一般答案.请注意,DatagramProtocol
比 Protocol
更容易使用,因为您已经拥有 DatagramProtocol
实例,而无需获得工厂的合作正如您在 Protocol
案例中所做的那样.
The UDP<->TCP specifics in this question don't break the general answer given in the FAQ entry. Just notice that a DatagramProtocol
is easier to work with than a Protocol
because you already have the DatagramProtocol
instance without having to get the cooperation of a factory as you do in the Protocol
case.
换一种说法:
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()
注意基本变化:UDPServer
需要调用 TCPServer
实例上的方法,因此它需要对该实例的引用.这是通过使 TCPServer
实例将自身传递给 UDPServer
初始化程序并使 UDPServer
初始化程序将该引用保存为 的属性来实现的>UDPServer
实例.
Notice the essential change: UDPServer
needs to call a method on an instance of TCPServer
so it needs a reference to that instance. This is achieved by making the TCPServer
instance pass itself to the UDPServer
initializer and making the UDPServer
initializer save that reference as an attribute of the UDPServer
instance.
这篇关于Twisted UDP to TCP Bridge的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!