最近,我第一次尝试使用Twisted/Python来构建一个应用程序,该应用程序可以将传入的UDP串出TCP端口。我以为这会很简单,但我还没能让它开始工作。下面的代码是修改后的TCP和UDP服务器一起运行的示例。我只是想在这两个人之间传递一些数据。任何帮助都将不胜感激。
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()发布于 2013-11-15 19:47:22
这实质上是常见的如何在一个连接上输入,从而在另一个连接上输出?
这个问题中的UDP<->TCP细节不会破坏FAQ条目中的一般答案。请注意,DatagramProtocol比Protocol更容易使用,因为您已经拥有了DatagramProtocol实例,而不必像在Protocol情况下那样得到工厂的合作。
换句话说:
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实例的属性来实现的。
https://stackoverflow.com/questions/20008281
复制相似问题