python项目实战:搭建小型WEB服务器

用socket 模拟一个微型的web服务器,当py脚本run起后,实微型web server架起了,然后用本地浏览器访问127.0.0.1:8080(web server的ip_port)时web服务器就会将网页内容传给浏览器,实现网页浏览

  1. 当get请求一个主页时,要完整的显示一个页面(包括文本、图片、css绚染等)是要get多次请求的。
  1. respone回复本地页网,open(filepath, rwa)时要特别的注意
import socket
import os
  
curfilepath = os.path.split(os.path.realpath(__file__))[0].replace("\\" , "/")
print(f'curfilepath: {curfilepath}')
  
  
def new_socket_server(new_socket, new_addr):
 if new_addr[0] != '':
 print(f'当前客户端{new_addr}已连接上server端. ')
  
 # 3.接收信息
 file_name = ''
 request_data = new_socket.recv(1024).decode('utf-8')
 if request_data != '':
 print(f'有收到新的信息,信息如下:\n{request_data}')
 file_name = request_data.splitlines()[0].split(' ')[1]
 print(f'file_name: {file_name}')
 if file_name == '/':
  file_name = '/index.html'
  print(f'file_name: {file_name}')
 with open(curfilepath + '/test.txt', 'a+') as f:
  f.write(file_name + '\n')
  
 # 4.回复信息
 try:
 f = open(curfilepath + '/htmltest' + file_name, 'rb')
 except:
 response = 'HTTP/1.1 404 NOT FOUND\r\n'
 response += '\r\n'
 response += '----------file not found-------'
 new_socket.send(response.encode('utf-8'))
 else:
 html_content = f.read()
 f.close()
 response = 'HTTP/1.1 200 OK\r\n' + '\r\n'
 new_socket.send(response.encode('utf-8'))
 new_socket.send(html_content)
  
  
def main():
 # 1.创建socket
 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  
 # 2.连接server
 server_ip_port = ('127.0.0.1', 8080)
 tcp_server_socket.bind(server_ip_port)
 tcp_server_socket.listen(128)
 while True:
 print('正在等待client端连接... ...')
 new_socket, new_addr = tcp_server_socket.accept()
 new_socket_server(new_socket, new_addr)
 new_socket.close()
  
  # 运行
if __name__ == '__main__':
 main()

本节分享结束,具有一定的借鉴价值,希望能够帮助到大家

你可能感兴趣的:(python项目实战:搭建小型WEB服务器)