我正在使用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-然後沒有特定的版本標籤;) –