我正在使用 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