python - 我需要发送不止一个 socket.send() 到一个 http 请求

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

我需要为我的 "Computers Network" class 创建一个基本的 http 服务器。 在我的项目中,客户端要求服务器(通过 GET 请求)发送文件。 服务器需要使用包含文件信息(例如文件大小、文件名)的 HTTP 响应进行响应,此外还应发送请求的文件。该文件可以来自任何类型(例如二进制、文本)。 根据我的理解,在我的例子中,客户端在每个 request.So 上只能得到一个服务器的响应,在收到带有文件数据的 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()

您希望发送的元数据可能会在 header response fields 中发送。文件大小本身进入 Content-Length(您已经在示例代码中发送),文件类型应作为 MIME 类型在 Content-Type 中给出,建议的文件名可以进入 Content-Disposition.

我应该提一下,每个 header 行必须由一对 CR-LF 终止,即 \r\n 并且最后的 header 行后面应该跟一个空白实际数据之前的行。换句话说,最后的 header 行后面应该跟一个额外的 CR-LF 对。

来自维基百科List of HTTP header fields:

The header fields are transmitted after the request or response line, which is the first line of a message. Header fields are colon-separated name-value pairs in clear-text string format, terminated by a carriage return (CR) and line feed (LF) character sequence. The end of the header section is indicated by an empty field, resulting in the transmission of two consecutive CR-LF pairs.