0

我正在使用 select() 函数在 python 中构建一个 Web 服务器 - I/O 多路复用。我能够连接到多个客户端,在我的情况下是 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
4

1 回答 1

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()
于 2013-02-06T02:29:45.200 回答