我需要为我的“计算机网络”类(class)创建一个基本的 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()
最佳答案
您希望发送的元数据可能会在 header response fields 中发送.文件大小本身在 Content-Length
中(您已经在示例代码中发送了),文件类型应在 Content-Type
中作为 MIME 类型给出,并且建议的文件名可以放在 Content-Disposition
中。
我应该提一下,每个标题行必须由一对 CR-LF 终止,即 \r\n
并且最后一个标题行应该在实际数据之前跟一个空行。换句话说,最后一个标题行后面应该跟一个额外的 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.
关于python - 我需要发送不止一个 socket.send() 到一个 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28124602/