我已經在python中創建了一個服務器,並且在請求文件時試圖將文件發送到客戶端。服務器收到請求,但不能通過TCP發送文件。無法通過python通過HTTP(通過TCP)發送文件。我的代碼有什麼問題?
我使用了一個模板來創建一個響應頭,然後我嘗試發送該文件,但它並不完全工作。我能夠「發送」.py和.html文件,而且它們在我的瀏覽器中顯示,但它一定是運氣,因爲根據我的技術援助,真正的測試是圖像...這不適合我。
首先,我將發佈標題和響應,如Firefox插件Firebug,然後是我的代碼,最後是錯誤消息。
Firebug的請求和響應
----------------------------
響應Headersview源
Accept-Ranges bytes
Connection Keep-Alive (or Connection: close)Content-Type: text/html; charset=ISO-8859-1
Content-Length 10000
Keep-Alive timeout=10, max=100
請求Headersview源
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Host xxx.xxx.244.5:10000
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
**我的Python代碼:**
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a server socket
serverPort = 10000
serverName = 'xxx.xxx.xxx.xx' #Laptop IP
serverSocket.bind((serverName,serverPort))
serverSocket.listen(5)
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print addr
try:
message = connectionSocket.recv(4096)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
f.close()
print 'length of output data: '
print len(outputdata)
print filename
print message
header = ("HTTP/1.1 200 OK\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length: 100000\r\n"
"Keep-Alive: timeout=10, max=100\r\n"
"Connection: Keep-Alive\r\n (or Connection: close)"
"Content-Type: text/html; charset=ISO-8859-1\r\n"
"\r\n")
connectionSocket.send(header)
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.sendall(outputdata[i])
connectionSocket.close()
print '\ntry code has executed\n'
except IOError:
print 'exception code has been executed'
connectionSocket.send('HTTP/1.1 404 Not found: The requested document does not exist on this server.')
connectionSocket.send('If you can read this, then the exception code has run')
print '\tconnectionSocket.send has executed'
connectionSocket.close()
print '\tconnectionSocket.close has executed\n'
#serverSocket.close()
這裏是錯誤消息:
此圖片 「http://xxx.xxx.244.5:10000/kitty.jpg」 無法顯示,因爲它包含錯誤。
預先感謝您!
WOWOWOWOW !!!!這工作。我花了兩天的時間試圖找出這一個!模板代碼(提供給我們修改的模板代碼在我粘貼它時寫下了這行代碼,非常感謝!現在我將閱讀python的文件處理過程......我想我沒有經驗來質疑模板。我在腳本中遇到了其他問題(如果我從客戶端取消文件傳輸,服務器崩潰,但我會在今天晚些時候嘗試解決這個問題)。您已經解決了我最大的問題! – newbie