2013-11-15 70 views
0

最近,我已經採取了我的第一個刺在Twisted/Python構建一個應用程序,從TCP端口迴應傳入的UDP字符串。我認爲這將會非常簡單,但我一直無法實現。下面的代碼是修改爲一起運行的示例TCP & UDP服務器。我只是想在兩者之間傳遞一些數據。任何幫助,將不勝感激。扭曲的UDP到TCP橋

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() 

回答

2

這在本質上是常見How do I make input on one connection result in output on another?

的UDP < - 在這個問題上不破的FAQ中給出的一般答案> TCP細節。請注意,DatagramProtocolProtocol更容易使用,因爲您已經擁有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實例的屬性來實現的。

+0

我已經看過這個例子,但是我的理解是DatagramProtocol不能/不使用工廠。當我試圖解決這個問題時,就像你分享的例子一樣,我得到了UDPServer不喜歡被共享工廠引用的錯誤。換言之,UDP打破了「一個連接,另一個輸出」的例子。 – SaranWrap