首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >双绞线UDP到TCP网桥

双绞线UDP到TCP网桥
EN

Stack Overflow用户
提问于 2013-11-15 18:40:16
回答 1查看 2.5K关注 0票数 0

最近,我第一次尝试使用Twisted/Python来构建一个应用程序,该应用程序可以将传入的UDP串出TCP端口。我以为这会很简单,但我还没能让它开始工作。下面的代码是修改后的TCP和UDP服务器一起运行的示例。我只是想在这两个人之间传递一些数据。任何帮助都将不胜感激。

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-15 19:47:22

这实质上是常见的如何在一个连接上输入,从而在另一个连接上输出?

这个问题中的UDP<->TCP细节不会破坏FAQ条目中的一般答案。请注意,DatagramProtocolProtocol更容易使用,因为您已经拥有了DatagramProtocol实例,而不必像在Protocol情况下那样得到工厂的合作。

换句话说:

代码语言:javascript
复制
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实例的属性来实现的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20008281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档