python制作网页服务器_python 编写简单网页服务器

原标题:python 编写简单网页服务器

IDE:Pycharm

sever.py

[python]view plaincopy

#!/bin/python

#-*- coding: UTF-8 -*-

#文件名:server.py

#create by wzh 2017/10/26

import socket #导入socket模块

import re

from multiprocessing import Process #导入进程模块

这个python学习(q-u-n):227-435-450 期待大家一起交流讨论,讲实话还是一个非常适合学习的地方的。各种入门资料啊,进阶资料啊,框架资料啊 爬虫等等

#设置静态文件根目录

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

html>

My Webtitle>head>

welcome!h1>

这是一个神奇的网站!p>

body>html>

运行server.py

在浏览器中输入localhost:1212返回搜狐,查看更多

责任编辑:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值