簡體   English   中英

我需要向一個http請求發送多個socket.send()

[英]python - I need to send more then one socket.send() to only one http request

我需要為我的“Computers Network”類創建一個基本的http服務器。 在我的項目中,客戶端要求服務器(通過GET請求)發送文件。 服務器需要響應HTTP響應,其中包含有關文件的信息(例如文件大小,文件名),此外它還應發送請求的文件。 該文件可以來自任何類型(例如二進制,文本)。 根據我的理解,客戶端每次請求只能獲得一個服務器的響應。所以在我的情況下,在收到帶文件數據的HTTP響應后,沒有收到實際文件。 有任何想法嗎?

我的服務器代碼:

import socket
import os
import sys

root = "J:\\Computers network  - Cyber\\HTTP-Server\\"
serverSocket=socket.socket()
serverSocket.bind(('0.0.0.0',8080))
serverSocket.listen(1)

(clientSocket, clientAddress)=serverSocket.accept()
clientRequest = clientSocket.recv(1024)

print clientRequest

requestSplit = clientRequest.split()

for i in xrange(2):
   if requestSplit[0] == "GET":

      response = "HTTP/1.1 200 OK\r\n" 

      if len(requestSplit[1]) > 1:

         fileRequestList = requestSplit[1].split('/')
         filePath = requestSplit[1].replace('/','\\')
         print "Client asked for " + filePath

         if os.path.isfile(root + filePath):

            try:
               # Writing the response
               fileSize = os.path.getsize(root + filePath) 
               response += "content-Length: " + str(fileSize) + "\r\n"
               print response
               clientSocket.send(response) 


               # Finding and sending the file name and the actual file
               print "File path " + filePath + " exists"
               f = open(root + filePath,'rb')
               fileToSend = f.read()
               print "The file path: " + filePath + "\n"
               clientSocket.send(root+filePath + "\n")
               clientSocket.send(fileToSend)


            except:                
               e = sys.exc_info()[0]
               print "ERROR is ==> " + str(e) + "\n"


         else:
            print "File path " + filePath + " does not exist"



      if i == 1:
         #for loop runs 2 times and only the cliest socket closing.
         clientSocket.close()

   else:
      # If the server did not got GET request the client socket closing.
      clientSocket.close()

   #fileToSend = ""
   #filePath = ""
serverSocket.close()

您希望發送的元數據可能會在標頭響應字段中發送。 文件大小本身位於Content-Length (您已在示例代碼中發送),文件類型應在Content-Type以MIME類型的形式給出,建議的文件名可以在Content-Disposition

我應該提到每個標題行必須由CR-LF對終止,即\\r\\n和最終標題行后面應該跟在實際數據之前的空白行。 換句話說,最后一個標題行后面應該有一個額外的CR-LF對。

來自Wikipedia HTTP標頭字段列表

標頭字段在請求或響應行之后傳輸,該行是消息的第一行。 標題字段是明文字符串格式的冒號分隔的名稱 - 值對,由回車符(CR)和換行符(LF)字符序列終止。 標題部分的末尾由空字段指示,導致兩個連續CR-LF對的傳輸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM