一、实验目的
-
学习如何创建套接字,将其绑在特定的地址和端口
-
学习如何发送和接收HTTP数据包
-
学习一些HTTP首部格式的基础知识
二、实验内容
-
开发一个处理一个HTTP请求的Web服务器。
-
Web服务器应该接受并解析HTTP请求,然后从服务器的文件系统获取所请求的文件,创建一个由响应文件组成的HTTP响应消息,前面是首部行,然后将响应直接发送给客户端。
-
如果请求的文件不存在于服务器中,则服务器应该向客户端发送“404 Not Found”差错报文。
三、实验原理(随便写写......)
C 库中包含了用语网络通信的 socket 套接字。Socket 套接字分为流式套接口、 数据报套接口及原始套接口 3 类。
HTTP协议工作原理。
四、实验步骤
根据提供的代码框架,完善代码,运行服务器,通过在主机上运行你的浏览器发送请求来测试该服务器。
五、实验结果及分析
Web服务器代码
#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
serverPort = 12345
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
#Fill in end
while True:
#Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024).decode()
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Send one HTTP header line into socket
#Fill in start
headerline = "HTTP/1.1 200 OK\r\n"
headerline += "Connection: close\r\nContent-Length: "
headerline += str(len(outputdata))
headerline += "\r\nContent-Type: text/html\r\n\r\n"
print(headerline)
connectionSocket.send(headerline.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("\r\n".encode())
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill in start
errinfo = 'HTTP/1.1 404 Not Found\r\n'
connectionSocket.send(errinfo.encode())
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
sys.exit()#Terminate the program after sending the corresponding data
测试结果
服务器端运行主机的IP地址
在浏览器中请求文件,成功
这是hello.html的内容
当请求不存在的文件时,返回404报文
六、实验中遇到的问题及解决方法
在本实验编写代码时,不清楚HTTP首部行具体包含哪些内容,在阅读教材并在网上查找相关资料后,选择了一些信息进行处理,并加入首部行。
七、实验心得体会
学习了如何用Python开发一个简单的Web服务器,并更进一步理解了socket套接字编程的应用和HTTP协议的工作原理。