计网课后编程作业
Web Server
在这个编程作业中,你将用Python语言开发一个简单的Web服务器,它仅能处理一个请求。具体而言,你的Web服务器将:(1)当一个客户(浏览器)联系时创建一个连接套接字;(2)从这个连接接收HTTP请求;(3)解释该请求以确定所请求的特定文件;(4)从服务器的文件系统获得请求的文件;(5)创建一个由请求的文件组成的HTTP响应报文,报文前面有首部行;(6)经TCP连接向请求的浏览器发送响应。如果浏览器请求一个在该服务器中不存在的文件,服务器应当返回一个“404 Not Found”差错报文。
在配套网站中,我们提供了用于该服务器的框架代码。你的任务是完善该代码,运行你的服务器,通过在不同主机上运行的浏览器发送请求来测试该服务器。如果运行你服务器的主机上已经有一个Web服务器在运行,你应当为该Web服务器使用一个不同于80端口的其他端口。
my first blog
这是我第一次尝试在CSDN上写一篇博客,我的主要目的就是记录一下我之前所学的内容以及对应的作业。事实上,主要是因为课程作业的代码在本地储存的多而杂,比较乱,之后想再翻出来看也找不到,所以放到这上面方便管理,也为了节省一下本地空间 😃 (虽然这些代码实际上并无多少占用😥)本地没有那么多文件夹看起来会舒服些。
原谅我只是代码的搬运工😭代码参考了同学的😨不过这些代码都是经过我亲自运行哒😆~~绝对没有问题,可以直接成功运行哒😎
如果没有问题就麻烦给个赞哦~
下面赶紧源码奉上:
源码
# Import socket module
from socket import *
import sys # In order to terminate the program
# Create a TCP server socket
# (AF_INET is used for IPv4 protocols)
# (SOCK_STREAM is used for TCP)
serverSocket = socket(AF_INET, SOCK_STREAM)
# Assign a port number
serverPort = 6789
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))
# Listen to at most 1 connection at a time
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections
while True:
print('The server is ready to receive')
# Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
# If an exception occurs during the execution of try clause
# the rest of the clause is skipped
# If the exception type matches the word after except
# the except clause is executed
try:
# Receives the request message from the client
message = connectionSocket.recv(1024).decode()
# Extract the path of the requested object from the message
# The path is the second part of HTTP header, identified by [1]
filename = message.split()[1]
# Because the extracted path of the HTTP request includes
# a character '\', we read the path from the second character
f = open(filename[1:])
# Store the entire contenet of the requested file in a temporary buffer
outputdata = f.read()
# Send the HTTP response header line to the connection socket
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())
# Send the content of the requested file to the connection socket
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
# Close the client connection socket
connectionSocket.close()
except IOError:
# Send HTTP response message for file not found
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n".encode())
# Close the client connection socket
connectionSocket.close()
serverSocket.close()
sys.exit() # Terminate the program after sending the corresponding data