WebServer
1. 实验目的
了解Python中的TCP套接字编程基础,包括创建套接字,将套接字保定到指定的地址与接口,以及收发包
了解一些 HTTP 首部行格式
2. 实验内容
开发一个网页服务器,单线程地处理HTTP请求
此服务器应该能完成以下工作
接收并分析 HTTP 请求
从本地文件系统中查找被请求地文件
创建包含首部行和请求文件内容的响应报文
将响应报文发送给客户端
当文件不存在时,应发送给客户端“404 Not Found”
3. 程序代码
#import socket module
from socket import *
import sys # In order to terminate the program
# 1. Create a socket for TCP connection
serverSocket = socket(AF_INET, SOCK_STREAM)# the parameters indicate this is a socket based on Ipv4 and TCP
# Prepare a server socket
serverPort = 6789
serverSocket.bind(('', serverPort))
serverSocket.listen(1) #the parameter specifies the number of unaccepted connections that the system will allow before refusing new connections
while True:
#2. Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
# 3. recieve a HTTP query
message = connectionSocket.recv(2048).decode()
print(message)
# 4. search the file in local system
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
# 5. create and send the response message
# Send one HTTP header line into socket
header = 'HTTP/1.1 200 OK\n'
header += 'Connection: close\n'
header += 'Content-Type: text/html\n'
header += 'Content-Length: %d\n\n' % (len(outputdata))
connectionSocket.send(header.encode())
# Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
#send the end message
connectionSocket.send("\r\n".encode())
except IOError:
#6. Send response message for file not found
connectionSocket.send('HTTP/1.1 404 Not Found'.encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
serverSocket.close()
sys.exit()#Terminate the program after sending the corresponding data
4. 实验过程
在主机上运行网页服务器代码 WebServer.py
通过浏览器访问服务器中的文件
http://localhost:6789/HelloWorld.html
http://localhost:6789/NotExisted.html
5. 实验结果
使用http://localhost:6789/HelloWorld.html成功地请求并加载了本地的页面
使用http://localhost:6789/HelloWorld.html得到404的提示
网页服务器接收的请求报文部分内容如下
GET /HelloWorld.html HTTP/1.1
Host: localhost:6789
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Cookie: _ga=GA1.1.873531135.1587267004; _gid=GA1.1.970751890.1594543167
6. 实验小结
掌握了如何使用Python创建基于TCP连接的服务器端套接字
对象 socket
方法 .bind() .listen() .accept() .send() .recv()
实际查看了 HTTP 的请求报文中的首行部信息,并在响应报文中编辑了相应的首部行
header = 'HTTP/1.1 200 OK\n'
header += 'Connection: close\n'
header += 'Content-Type: text/html\n'
header += 'Content-Length: %d\n\n' % (len(outputdata))