Python 扭曲UDP到TCP网桥
最近,我第一次尝试Twisted/Python构建一个应用程序,该应用程序在TCP端口上回显传入的UDP字符串。我以为这会很简单,但我一直没能让它工作。下面的代码是修改为一起运行的TCP和UDP服务器示例。我只是想在两者之间传递一些数据。任何帮助都将不胜感激Python 扭曲UDP到TCP网桥,python,tcp,udp,twisted,tunnel,Python,Tcp,Udp,Twisted,Tunnel,最近,我第一次尝试Twisted/Python构建一个应用程序,该应用程序在TCP端口上回显传入的UDP字符串。我以为这会很简单,但我一直没能让它工作。下面的代码是修改为一起运行的TCP和UDP服务器示例。我只是想在两者之间传递一些数据。任何帮助都将不胜感激 from twisted.internet.protocol import Protocol, Factory, DatagramProtocol from twisted.internet import reactor class TC
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()
这基本上是常见问题 这个问题中的UDPTCP细节并没有破坏FAQ条目中给出的一般答案。请注意,
DatagramProtocol
比协议
更容易使用,因为您已经拥有了DatagramProtocol
实例,而不必像在协议
案例中那样获得工厂的合作
换句话说:
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
实例的属性来实现的。我以前看过该示例,但据我所知,DatagramProtocol不能/不能使用工厂。当我试图像您共享的示例那样解决这个问题时,我遇到了UDPServer不喜欢被共享工厂引用的错误。说另一种方式UDP中断“一个连接,另一个输出”的例子。