【问题标题】:Echoing messages received through UDP back through a different TCP port通过不同的 TCP 端口回显通过 UDP 接收的消息
【发布时间】:2015-07-14 13:27:24
【问题描述】:

我使用 Python 2.7.x (2.7.8) 并尝试使用 twisted python 编写一个程序来实现如下功能:

  • 程序等待通过 TCP 7001 或 UDP 7000 接收到的消息。
  • 通过 UDP 7000 接收的消息被桥接到 TCP 7001 出去。

我不知道如何将 UDP 桥接到 TCP,所以我在这个站点上查找了一个示例,例如这个,Twisted UDP to TCP Bridge,但问题是该示例是在撒谎,因为它不起作用。我在 datagramReceived 上添加了一个“打印数据报”,以查看 UDP 是否响应接收任何东西,但它没有。这完全令人沮丧。

这是我当前的测试代码,与该示例相比稍作修改

from twisted.internet.protocol import Protocol, Factory, DatagramProtocol
from twisted.internet import reactor

class TCPServer(Protocol):
    def connectionMade(self):
        self.port = reactor.listenUDP(7000, UDPServer(self))

    def connectionLost(self, reason):
        self.port.stopListening()

    def dataReceived(self, data):
        print "Server said:", data


class UDPServer(DatagramProtocol):
    def __init__(self, stream):
        self.stream = stream

    def datagramReceived(self, datagram, address):
        print datagram
        self.stream.transport.write(datagram)


def main():
    f = Factory()
    f.protocol = TCPServer
    reactor.listenTCP(7001, f)
    reactor.run()

if __name__ == '__main__':
    main()

如您所见,我更改了端口以符合我的测试环境并添加了打印数据报以查看是否有任何调用 datagramReceived。我向这个程序发送 TCP 东西没有问题,TCPServer 工作得很好,因为可以调用 dataReceived。

【问题讨论】:

  • 这里的想法是UDP/7000 上的传入消息被路由到绑定到TCP/700 的侦听服务器上的连接客户端吗?
  • 端口不同有关系吗?是的,这就是我想要做的。我的印象是示例链接“桥接 UDP 到 TCP”就是这样做的。
  • 我是circuits 的开发人员,可以工作:gist.github.com/prologic/ae987fe4f6fbbd9ca415 -- 我还没有测试过这个:)

标签: python sockets networking udp twisted


【解决方案1】:

我运行了您问题中的代码(稍作修改:我启用了日志记录)。我使用telnet 连接到端口 7001 上的 TCP 服务器。我使用 Python REPL 创建了一个 UDP 套接字并将一些数据报发送到端口 7000。

这是我的 REPL 成绩单:

>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> s.sendto('hello', ('127.0.0.1', 7000))
5
>>> s.sendto('world', ('127.0.0.1', 7000))
5
>>> 

这是我的服务器日志(格式适合您的屏幕):

... Log opened.
... Factory starting on 7001
... Starting factory <twisted.internet.protocol.Factory instance at 0x2b9b128>
... UDPServer  starting on 7000
... Starting protocol <__main__.UDPServer instance at 0x2e8f8c0>
... hello
... world

这是我的 telnet 会话记录:

$ telnet localhost 7001
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
helloworld

我对这些结果的解释是程序实际上按规定工作。我想知道当你尝试产生不同的、无效的结果时,你做了什么不同的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多