3

我正在python中使用twisted 10学习网络编程。在下面的代码中,有没有办法在收到数据时检测 HTTP 请求?还从中检索域名、子域、端口值吗?如果不是http数据就丢弃它?

from twisted.internet import stdio, reactor, protocol

from twisted.protocols import basic

import re



class DataForwardingProtocol(protocol.Protocol):

    def _ _init_ _(self):

        self.output = None

        self.normalizeNewlines = False



    def dataReceived(self, data):

        if self.normalizeNewlines:

            data = re.sub(r"(\r\n|\n)", "\r\n", data)

        if self.output:

            self.output.write(data)



class StdioProxyProtocol(DataForwardingProtocol):

    def connectionMade(self):

        inputForwarder = DataForwardingProtocol( )

        inputForwarder.output = self.transport

        inputForwarder.normalizeNewlines = True

        stdioWrapper = stdio.StandardIO(inputForwarder)

        self.output = stdioWrapper

        print "Connected to server.  Press ctrl-C to close connection."



class StdioProxyFactory(protocol.ClientFactory):

    protocol = StdioProxyProtocol



    def clientConnectionLost(self, transport, reason):

        reactor.stop( )



    def clientConnectionFailed(self, transport, reason):

        print reason.getErrorMessage( )

        reactor.stop( )



if __name__ == '_ _main_ _':

    import sys

    if not len(sys.argv) == 3:

        print "Usage: %s host port" % _ _file_ _

        sys.exit(1)



    reactor.connectTCP(sys.argv[1], int(sys.argv[2]), StdioProxyFactory( ))

    reactor.run( )
4

2 回答 2

3

您要覆盖的protocol.dataReceived太低级,无法在没有您没有做的智能缓冲的情况下用于此目的——根据我刚刚引用的文档,

每当接收到数据时调用。

使用此方法可以转换为更高级别的消息。通常,在收到每条完整的协议消息时都会进行一些回调。

参数

data

一个不确定长度的字符串。请记住,您可能需要缓冲一些数据,因为可能会收到部分(或多个)协议消息!我建议协议的单元测试以不同的块大小调用此方法,一次低至一个字节。

您似乎完全忽略了文档的这一关键部分。

您可以改为使用LineReceiver.lineReceived(当然,继承自protocols.basic.LineReceiver)来利用 HTTP 请求以“行”形式出现的事实——您仍然需要将作为多行发送的标头连接起来,因为这样教程说:

以空格或制表符开头的标题行实际上是前一个标题行的一部分,折叠成多行以便于阅读。

一旦你有一个很好的格式化/解析的响应(考虑研究twisted.web的来源,看看可以做到的一种方法),

从中检索域名、子域、端口值?

现在Host标题(cfr RFC 14.23 节)是包含此信息的标题。

于 2010-08-07T14:39:00.153 回答
1

仅基于您似乎正在尝试的内容,我认为以下将是阻力最小的路径:http: //twistedmatrix.com/documents/10.0.0/api/twisted.web.proxy.html

这是构建 HTTP 代理的扭曲类。它会让你拦截请求,查看目的地并查看发送者。您还可以查看所有标题和来回显示的内容。您似乎正在尝试重新编写 twisted 已经为您提供的 HTTP 协议和代理类。我希望这有帮助。

于 2010-08-10T18:53:12.553 回答