计算机网络自顶向下方法
套接字编程作业 Web服务器(单线程)
需求:
完整代码:
import time
# import socket module
from socket import *
import sys # In order to terminate the program
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
# Fill in start
severPort=6789
serverSocket.bind(('',severPort))
serverSocket.listen(1)
# Fill in end
while True:
# Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept() # Fill in start #Fill in end
message = connectionSocket.recv(1024*1024).decode()# Fill in start #Fill in end/
message = message.split()
if len(message)<2:
continue
filename = message[1] #报文的第一个词是get,第二个词是文件位置
try:
f = open(filename[1:],"r",encoding='utf-8') #文件位置以/开头
# Fill in start
outputdata = []
size=0
while True:
s = f.read(1024)
if len(s) == 0:
break
outputdata.append(s)
size+=len(s)
#Fill in end
f.close()
# Send one HTTP header line into socket
# Fill in start
head=""
head+=message[2]
head+=" 200 OKrn"
head+="Connection: closern"
head+="Date: "+time.strftime("%a, %d %b %Y %H:%M:%S GMT+8rn", time.localtime())
head += "Server: liuxiangbin's laptoprn"
# head+="Last-Modified: "+time.strftime("%a, %d %b %Y %H:%M:%S GMT+8rn", time.localtime())
head+="Content-Length: "+str(size)+"rn"
head+="Content-Type: text/htmlrnrn"
connectionSocket.send(head.encode())
# Fill in end
# Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("rn".encode())
connectionSocket.close()
# Send response message for file not found
# Fill in start
except FileNotFoundError:
head=""
head+=message[2]
head+=" 404 Not Foundrn"
head+="Connection: closern"
head+="Date: "+time.strftime("%a, %d %b %Y %H:%M:%S GMT+8rn", time.localtime())
head += "Server: liuxiangbin's laptoprn"
# head+="Last-Modified: "+time.strftime("%a, %d %b %Y %H:%M:%S GMT+8rn", time.localtime())
# head+="Content-Length: "+str(size)+"rn"
head+="Content-Type: text/htmlrnrn"
connectionSocket.send(head.encode())
# Fill in end
# Close client socket
# Fi6ll in start
connectionSocket.close()
# Fill in end
serverSocket.close()
sys.exit() # Terminate the program after sending the corresponding data



