通过UDP回送通过不同TCP端口回收的消息

Non*_*ame 5 python sockets networking udp twisted

我使用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()
Run Code Online (Sandbox Code Playgroud)

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

Jea*_*one 3

我运行了您问题中的代码(稍作修改:我启用了日志记录)。我曾经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
>>> 
Run Code Online (Sandbox Code Playgroud)

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

... 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
Run Code Online (Sandbox Code Playgroud)

这是我的 telnet 会话记录:

$ telnet localhost 7001
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
helloworld
Run Code Online (Sandbox Code Playgroud)

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