登录  /  注册

python 编写简单网页服务器

不言
发布: 2018-06-02 14:23:49
原创
2676人浏览过

这篇文章主要介绍了关于python 编写简单网页服务器,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

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 编写简单网页服务器的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号