You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
p2l5wexnu/code/reference/ch_socket/Webserver.py

51 lines
1.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from socket import *
import sys
# 准备服务器端 socket
serverSocket = socket(AF_INET, SOCK_STREAM)
# 设定端口号
serverPort = 80
# 绑定地址host,port到套接字
serverSocket.bind(("localhost", serverPort))
# 开始 TCP 监听,该值至少为 1
serverSocket.listen(1)
while True:
# 建立连接
print('Ready to serve...')
# 收到客户端请求时建立一个新连接
connectionSocket, addr = serverSocket.accept()
try:
# 按需补充,接受来自客户端的请求
message = connectionSocket.recv(1024).decode()
# 从消息中提取所请求对象的路径
# 路径是HTTP标头的第二部分由[1]标识
filename = message.split()[1]
# 因为HTTP请求的提取路径包括一个字符“ \”,我们从第二个字符读取路径
f = open(filename[1:])
# 将请求文件的全部内容存储在临时缓冲区中
outputdata = f.read()
# 将HTTP响应标头行发送到连接套接字
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())
# 将请求文件的内容发送到客户端
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
# 按需补充代码:发送未找到文件的响应消息
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())
# 按需补充代码:关闭客户端 socket
connectionSocket.close()
serverSocket.close()
sys.exit()