python 编写简单网页服务器的实例
程序员文章站
2023-11-24 17:44:34
ide:pycharm
sever.py
#!/bin/python
#-*- coding: utf-8 -*-
#文件名:server.py
#cre...
ide:pycharm
sever.py
#!/bin/python #-*- coding: utf-8 -*- #文件名:server.py #create by wzh 2017/10/26 import socket #导入socket模块 import re from multiprocessing import process #导入进程模块 #设置静态文件根目录 html_root_dir='./html' def handle_client(client_socket): """处理客户端连接请求""" request_data=client_socket.recv(1024) print(request_data) request_lines=request_data.splitlines() for line in request_lines: print(line) #'get / http/1.1' request_start_line=request_lines[0].decode("utf-8") print("*"*10) print(request_start_line) #提取用户请求的文件名 file_name=re.match(r"\w+ +(/[^ ]*) ",str(request_start_line)).group(1) if "/" == file_name: file_name='/index.html' #打开文件,读取内容 try: file=open(html_root_dir+file_name,"rb") except ioerror: response_start_line="http/1.1 404 not found\r\n" response_heads="server: my server\r\n" response_body="the file not found!" else: file_data=file.read() file.close() response_start_line="http/1.1 200 ok\r\n" response_heads="server: my server\r\n" response_body=file_data.decode("utf-8") response=response_start_line+response_heads+"\r\n"+response_body print("response data:",response) client_socket.send(bytes(response,"utf-8")) client_socket.close() if __name__=="__main__": #如果直接运行本文件,那么__name__为__main__(此时才运行下面的程序),否则为对应包名 s = socket.socket(socket.af_inet,socket.sock_stream) # 创建socket对象 s.setsockopt(socket.sol_socket,socket.so_reuseaddr,1) #host = socket.gethostname() # 获取本地主机名 port = 1212 # #print(host) s.bind(("", port)) # 绑定端口 s.listen(5) while true: c,addr=s.accept() #建立客户端连接 print('连接地址',addr) handle_client_process=process(target=handle_client,args=(c,)) #alt+enter快捷键生成函数 handle_client_process.start() c.close()
index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>my web</title> </head> <h1 align="center">welcome!</h1> <p align="center">这是一个神奇的网站!</p> <body> </body> </html>
运行server.py
在浏览器中输入localhost:1212
以上这篇python 编写简单网页服务器的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。