"컴퓨터 네트워크"클래스에 대한 기본 http 서버를 만들어야합니다. 내 프로젝트에서 클라이언트는 GET 요청을 통해 서버에 파일을 보내도록 요청합니다. 서버는 파일에 대한 정보 (예 : 파일 크기, 파일 이름)를 포함하는 HTTP 응답으로 응답해야하며 요청 된 파일도 보내야합니다. 파일 형식 (예 : 바이너리, 텍스트) 일 수 있습니다. 내 이해에서 클라이언트가 모든 요청에 단 하나의 서버의 응답을 얻을 수 있습니다. 내 경우에는 파일 데이터와 HTTP 응답을받은 후 실제 파일을받지 않습니다. 아이디어가 있으십니까?python - 하나의 http 요청에만 socket.send()를 더 보내야합니다.
내 서버의 코드 :
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()
높은 수준에서 볼 때 클라이언트에서 2 개의 요청을 사용하는 방법 (이름이 충분하지 않고 두 번째로 실제 데이터를 가져 오는 경우 메타 데이터, 이름, 크기 및 ID를 먼저 얻음) 또는 메타 데이터와 데이터 (XML, json 또는 bson 형식을 생각하는)를 모두 포함하는 stuctured 응답을 사용하십시오. –