Python 2.7中的Web服务器:浏览器不显示页面

时间:2013-02-06 01:15:39

标签: python python-2.7 network-programming

我正在使用select()函数--I / O多路复用在python中构建一个Web服务器。我能够连接到多个客户端,在我的例子中是Web浏览器(safari,chrome,firefox)并接受每个客户端HTTP 1.1 GET请求。收到请求后,我将html页面内容返回到显示html页面的浏览器。

我遇到的问题是当我尝试保持连接打开一段时间。我意识到在使用fd.close()关闭连接之前,我无法在浏览器中显示任何内容。

以下是我用来接受和回复浏览器请求的功能。问题是在我使用fd.sendall()后,我不想关闭连接,但页面不会显示,直到我这样做。请帮忙!任何帮助或建议都表示赞赏..

def handleConnectedSocket():
    try:
        recvIsComplete = False
        rcvdStr = ''

        line1 = "HTTP/1.1 200 OK\r\n"
        line2 = "Server: Apache/1.3.12 (Unix)\r\n"
        line3 = "Content-Type: text/html\r\n" # Alternately, "Content-Type: image/jpg\r\n"
        line4 = "\r\n"

        line1PageNotFound = "HTTP/1.1 404 Not Found\r\n"
        ConnectionClose = "Connection: close\r\n"

        while not recvIsComplete:
            rcvdStr = fd.recv( 1024 )

            if rcvdStr!= "" :

# look for the string that contains the html page
                recvIsComplete = True
                RequestedFile = ""
                start = rcvdStr.find('/') + 1 
                end = rcvdStr.find(' ', start)
                RequestedFile = rcvdStr[start:end] #requested page in the form of xyz.html

                try:
                    FiletoRead = file(RequestedFile , 'r')
                except:
                    FiletoRead = file('PageNotFound.html' , 'r')
                    response = FiletoRead.read()
                    request_dict[fd].append(line1PageNotFound + line2 + ConnectionClose + line4) 
                    fd.sendall( line1PageNotFound + line2 + line3 + ConnectionClose + line4 + response )
#                    fd.close()   <--- DONT WANT TO USE THIS
                else:    
                    response = FiletoRead.read()
                    request_dict[fd].append(line1 + line2 + line3 + ConnectionClose + line4 + response)
                    fd.sendall(line1 + line2 + line3 + line4 + response)
#                    fd.close()   <--- DONT WANT TO USE THIS
            else:
                recvIsComplete = True
#Remove messages from dictionary
                del request_dict[fd]    
                fd.close()

客户端(浏览器)请求采用HTTP 1.1格式,如下所示:

GET /Test.html HTTP/1.1
Host: 127.0.0.1:22222
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8) AppleWebKit/536.25 (KHTML, like    Gecko) Version/6.0 Safari/536.25
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: keep-alive

1 个答案:

答案 0 :(得分:1)

Connection: close向浏览器表明,当您通过关闭连接完成数据发送时,您将告诉它。由于您不想这样做,因此您可能希望为Connection使用不同的值,例如Keep-Alive。但是,如果您使用它,那么您还需要发送Content-Length或执行其他操作,以便浏览器知道您何时完成数据发送。

即使您没有使用Keep-AliveContent-Length也是一件好事,因为它允许浏览器知道下载页面的当前进度。如果您要发送大文件而不发送Content-Length,则浏览器不能显示进度条。 Content-Length可以实现这一点。

那么如何发送Content-Length标题?计算您要发送的数据的字节数。将其转换为字符串并将其用作值。就这么简单。例如:

# Assuming data is a byte string.
# (If you're dealing with a Unicode string, encode it first.)
content_length_header = "Content-Length: {0}\r\n".format(len(data))

以下是一些适合我的代码:

#!/usr/bin/env python3
import time
import socket

data = b'''\
HTTP/1.1 200 OK\r\n\
Connection: keep-alive\r\n\
Content-Type: text/html\r\n\
Content-Length: 6\r\n\
\r\n\
Hello!\
'''


def main(server_address=('0.0.0.0', 8000)):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    server.bind(server_address)
    server.listen(5)
    while True:
        try:
            client, client_address = server.accept()
            handle_request(client, client_address)
        except KeyboardInterrupt:
            break


def handle_request(client, address):
    with client:
        client.sendall(data)
        time.sleep(5)  # Keep the socket open for a bit longer.
        client.shutdown(socket.SHUT_RDWR)


if __name__ == '__main__':
    main()