python 编写简单网页服务器的实例

yipeiwu_com5年前服务器

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 编写简单网页服务器的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)

python网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)

UDP广泛应用于需要相互传输数据的网络应用中,如QQ使用的就是UDP协议。在网络质量不好的情况下,使用UDP协议时丢包现象十分严重,但UDP占用资源少,处理速度快,UDP依然是传输数据时...

利用Python如何批量更新服务器文件

前言 买了个Linux服务器,Centos系统,装了个宝塔搭建了10个网站,比如有时候要在某个文件上加点代码,就要依次去10个文件改动,虽然宝塔是可视化页面操作,不需要用命令,但是也麻烦...

php模拟服务器实现autoindex效果的方法

php模拟服务器实现autoindex效果的方法

本文实例讲述了php模拟服务器实现autoindex效果的方法。分享给大家供大家参考。具体实现方法如下: 1.PHP代码如下: 复制代码 代码如下:<?php //文件浏...

PHP 显示客户端IP与服务器IP的代码

来看看代码: 复制代码 代码如下: echo "(1)浏览当前页面的用户的 IP 地址为:"; echo $_SERVER['REMOTE_ADDR']; echo "<br /&...

Linux下将Python的Django项目部署到Apache服务器

这几天花了点时间,将把django开发好的web项目部署到Apache上,参考了官方的一些文档和互联网上的文档,还是花了比较多的时间,这里把配置的过程说一下。 方便有需要的朋友,可以参考...