python3实现微型的web服务器

yipeiwu_com6年前服务器

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

sw+sys: python3.7.2 + windows10 64bit

本地准备的server端网页为下载的hao123主页(我已上载并上传,点击这里

通过这个实验让我学到了:

1. 当get请求一个主页时,要完整的显示一个页面(包括文本、图片、css绚染等)是要get多次请求的。

2. 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设计】。

相关文章

python3实现UDP协议的服务器和客户端

利用Python中的socket模块中的来实现UDP协议,这里写一个简单的服务器和客户端。为了说明网络编程中UDP的应用,这里就不写图形化了,在两台电脑上分别打开UDP的客户端和服务端就...

Python基于select实现的socket服务器

本文实例讲述了Python基于select实现的socket服务器。分享给大家供大家参考,具体如下: 借鉴了asyncore模块中select.select的使用方法 import...

python基于paramiko将文件上传到服务器代码实现

python通过安装使用paramiko模块,将本地文件上传到服务器上 import paramiko import datetime import os hostname = '...

使用php判断服务器是否支持Gzip压缩功能

Gzip可以压缩网页大小从而达到加速打开网页的速度,目前主流的浏览器几乎都支持这个功能,但开启Gzip是需要服务器支持的,在这里我们简单的使用php来判断服务器是否支持Gzip功能。 新...

Pycharm连接远程服务器并实现远程调试的实现

Pycharm连接远程服务器并实现远程调试的实现

当需要远程办公时,使用pycharm远程连接服务器时必要的。 PyCharm提供两种远程调试(Remote Debugging)的方式: 配置远程的解释器(remote inter...