2010-08-07 77 views
3

我正在学习在python中使用扭曲10的网络编程。在下面的代码中,有什么方法可以在数据收到时检测HTTP请求?还从这个检索域名,子域,端口值?丢弃它,如果它不是http数据?如何检测Python中的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() 

回答

3

protocol.dataReceived,你要覆盖,太级低,以服务为没有说你没有做智能缓存的目的 - 每次我刚引述的文档,

调用每当收到数据时。

使用此方法转换为 更高级别的消息。通常,一旦收到每个完整协议消息的收据 ,就会进行一些回拨。

参数

data 

不确定长度的字符串。请注意保留在 的脑海中,您可能需要将 缓存一些数据,因为部分(或多个 )协议消息可能是 收到的!我建议单元测试 协议通过调用这个 方法不同的块大小, 一次只能一个字节。

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

您可以改为使用LineReceiver.lineReceived(当然,从protocols.basic.LineReceiver继承)利用HTTP请求以“行”形式出现的优势 - 您仍需要加入以多​​行形式发送的标头,因为作为this tutorial说:开头的空格或标签

标题行实际上是先前 标题行的部分,折叠成多个 线为方便阅读。

一旦你有一个很好的格式化/解析的响应(考虑研究twisted.web's sources所以看一个方式,它可以做),

取回域名,二级域名,从这个端口 值?

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

+0

感谢alex的回复。你的回答对于像我这样的新手来说非常有用。我会接受它:) – 2010-08-08 06:22:43

+0

没问题,实际上我花了很多时间来解决类似的问题,并让自己的HTTP代理工作。一旦你发现它非常光滑。 – themaestro 2010-08-11 21:55:39

1

正是基于你似乎试图什么,我觉得有以下将是阻力最小的路径: http://twistedmatrix.com/documents/10.0.0/api/twisted.web.proxy.html

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