Python代理HTTP非常

2024-04-25 06:37:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python创建一个HTTP代理。在

不过,当我用这个代理配置我的浏览器并尝试连接到http网站时,加载速度非常慢。在

这是我的代理代码:

#!/usr/bin/env python

import socket
import thread
import sys

def get_line(field, data) :
    lines = data.split("\n")
    for line in lines :
        if line.split(":")[0] == field :
            return line
    return ""

def get_host(data) :
    host_line = get_line("Host", data);
    port = 80
    if len(host_line.split(" ")) > 1 :
        host = host_line.split(" ")[1]
        arr = host.split(":")
        if len(arr) > 1 :
            host = arr[0]
            port = arr[1]
        else :
            host = host[:-1]
    else :
        host = ""
        port = 0
    return (host, port)

def http_proxy(conn, data, client_addr) :
    (host, port) = get_host(data)
    if host != "" :
        try :
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((socket.gethostbyname(host), int(port)))
            s.send(data)
            while 1 : 
                reply = s.recv(8192)
                test = reply
                if (len(reply) > 0) :
                    conn.send(reply)
                    print "Send %d bytes from %s" % (len(reply), host)
                else :
                    conn.close()
                    s.close()
                    break
        except socket.error, (value, message) :
            s.close()
            conn.close()
            print value, message
            sys.exit(1)

def main():
    try :
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', 8080))
        s.listen(100)
    except socket.error, (value, message) :
        if s : 
            s.close()
        print "Socket error : ", message
    while 1 :
        conn, client_addr = s.accept()
        data = conn.recv(8192)
        thread.start_new_thread(http_proxy, (conn, data, client_addr))
    s.close()

if __name__ == "__main__" :
    main()

我认为这些延迟是由于我的代理没有考虑某些HTTP请求,所以浏览器在发送它们之前要等待一段时间。在

如果这就是问题所在,我不明白为什么会这样。在


Tags: host代理closedatagetlenifport