我正在使用select()函数--I/O多路复用在python中构建Web服务器。我能够连接到多个客户端,在我的情况下是web浏览器(safari,chrome,firefox),并接受每个客户端的HTTP 1.1 GET请求。一旦我收到请求,我将html页面内容返回到显示html页面的浏览器。Python 2.7中的Web服务器:浏览器不显示页面
我得到的问题是当我尝试保持连接打开一段时间。我意识到我无法在浏览器中显示任何内容,除非我使用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
你压痕有点混了(看看你的',而不是recvIsComplete'部分) - 也'file' (推荐使用“open”),所以我不认为你需要一个'python-3.x'标签,所以我已经删除它了。 –
我添加了python 3.x,因为我认为这个问题不仅仅是python 2.7相关。我正在寻找建议和任何建议,我如何解决这个问题。即使是一个python 3.x人也可以提出解决方案。 – CarbonD1225
Okies-然后没有特定的版本标签;) –