我需要向一个http请求发送多个socket.send()

时间:2015-01-24 10:40:28

标签: python sockets http httpresponse httpserver

我需要为我的"计算机网络"创建一个基本的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()

1 个答案:

答案 0 :(得分:3)

您希望发送的元数据可能会在header response fields中发送。文件大小本身位于Content-Length(您已在示例代码中发送),文件类型应在Content-Type中以MIME类型的形式给出,建议的文件名可以在{{ 1}}。

我应该提到每个标题行必须由CR-LF对终止,即Content-Disposition,最后的标题行后面应该跟在实际数据之前的空白行。换句话说,最后一个标题行后面应该有一个额外的CR-LF对。

来自维基百科List of HTTP header fields

  

标头字段在请求或响应行之后传输,这是消息的第一行。标题字段是明文字符串格式的冒号分隔的名称 - 值对,由回车符(CR)和换行符(LF)字符序列终止。标题部分的结尾由空字段指示,导致两个连续CR-LF对的传输。

相关问题