[英]Twisted UDP to TCP Bridge
最近,我第一次嘗試使用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()
這基本上是經常被問到如何在一個連接上輸入結果導致另一個連接上的輸出?
此問題中的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
實例的屬性來實現的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.