Python实现简单HTTP服务器(一)

一.返回固定内容

复制代码

coding:utf-8

import socket

from multiprocessing import Process

def handle_client(client_socket):

"""

处理客户端请求

"""

request_data = client_socket.recv(1024)

print("request data:", request_data)

# 构造响应数据

response_start_line = "HTTP/1.1 200 OK\r\n"

response_headers = "Server: My server\r\n"

response_body = "

Python HTTP Test

"

response = response_start_line + response_headers + "\r\n" + response_body

# 向客户端返回响应数据
client_socket.send(bytes(response, "utf-8")) # 关闭客户端连接
client_socket.close()

if name == "main":

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.bind(("", 8000))

server_socket.listen(128)

while True:
client_socket, client_address = server_socket.accept()
print("[%s, %s]用户连接上了" % client_address)
handle_client_process = Process(target=handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close()

复制代码

运行程序,打开浏览器输入:http://127.0.0.1:8000/,显示如下:

二.返回静态文件内容

复制代码

coding:utf-8

import 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_data)

request_lines = request_data.splitlines()

# 解析请求报文

request_start_line = request_lines[0]

# 提取用户请求的文件名

file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).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_headers = "Server: My server\r\n"
response_body = "The file is not found!"
else:
file_data = file.read()
file.close() # 构造响应数据
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n"
response_body = file_data.decode("utf-8") response = response_start_line + response_headers + "\r\n" + response_body
print("response data:", response) # 向客户端返回响应数据
client_socket.send(bytes(response, "utf-8")) # 关闭客户端连接
client_socket.close()

if name == "main":

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server_socket.bind(("", 8000))

server_socket.listen(128)

while True:
client_socket, client_address = server_socket.accept()
print("[%s, %s]用户连接上了" % client_address)
handle_client_process = Process(target=handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close()

复制代码

在程序所在目录下新建文件夹(html),里面放入HTML文件,运行程序,打开浏览器输入:http://127.0.0.1:8000/,显示如下:

改为面向对象的程序:

复制代码

coding:utf-8

import socket

import re

from multiprocessing import Process

设置静态文件根目录

HTML_ROOT_DIR = "./html"

class HTTPServer(object):

def init(self):

self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

def start(self):
self.server_socket.listen(128)
while True:
client_socket, client_address = self.server_socket.accept()
print("[%s, %s]用户连接上了" % client_address)
handle_client_process = Process(target=self.handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close() def handle_client(self, client_socket):
"""
处理客户端请求
"""
# 获取客户端请求数据
request_data = client_socket.recv(1024)
print("request data:", request_data)
request_lines = request_data.splitlines()
# 解析请求报文
request_start_line = request_lines[0]
# 提取用户请求的文件名
file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).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_headers = "Server: My server\r\n"
response_body = "The file is not found!"
else:
file_data = file.read()
file.close() # 构造响应数据
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n"
response_body = file_data.decode("utf-8") response = response_start_line + response_headers + "\r\n" + response_body
print("response data:", response) # 向客户端返回响应数据
client_socket.send(bytes(response, "utf-8")) # 关闭客户端连接
client_socket.close() def bind(self, port):
self.server_socket.bind(("", port))

def main():

http_server = HTTPServer()

http_server.bind(8000)

http_server.start()

if name == "main":

main()

复制代码

三.返回动态内容(运用wsgi)

复制代码

coding:utf-8

import socket

import re

import sys

from multiprocessing import Process

设置静态文件根目录

HTML_ROOT_DIR = "./html"

设置动态文件根目录

WSGI_PYTHON_DIR = "./wsgitest"

class HTTPServer(object):

def init(self):

self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

def start(self):
self.server_socket.listen(128)
while True:
client_socket, client_address = self.server_socket.accept()
print("[%s, %s]用户连接上了" % client_address)
handle_client_process = Process(target=self.handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close() def start_response(self, status, headers):
response_headers = "HTTP/1.1 " + status + "\r\n"
for header in headers:
response_headers += "%s: %s\r\n" % header self.response_headers = response_headers def handle_client(self, client_socket):
"""
处理客户端请求
"""
# 获取客户端请求数据
request_data = client_socket.recv(1024)
print("request data:", request_data)
request_lines = request_data.splitlines()
for line in request_lines:
print(line) # 解析请求报文
request_start_line = request_lines[0]
# 提取用户请求的文件名及请求方法
file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
method = re.match(r"(\w+) +/[^ ]* ", request_start_line.decode("utf-8")).group(1) # 处理动态文件
if file_name.endswith(".py"):
try:
m = __import__(file_name[1:-3])
except Exception:
self.response_headers = "HTTP/1.1 404 Not Found\r\n"
response_body = "not found"
else:
env = {
"PATH_INFO": file_name,
"METHOD": method
}
response_body = m.application(env, self.start_response) response = self.response_headers + "\r\n" + response_body
# 处理静态文件
else:
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_headers = "Server: My server\r\n"
response_body = "The file is not found!"
else:
file_data = file.read()
file.close() # 构造响应数据
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n"
response_body = file_data.decode("utf-8") response = response_start_line + response_headers + "\r\n" + response_body
print("response data:", response) # 向客户端返回响应数据
client_socket.send(bytes(response, "utf-8")) # 关闭客户端连接
client_socket.close() def bind(self, port):
self.server_socket.bind(("", port))

def main():

sys.path.insert(1, WSGI_PYTHON_DIR)

http_server = HTTPServer()

http_server.bind(8000)

http_server.start()

if name == "main":

main()

复制代码

在程序所在目录下新建文件夹(wsgitest),里面放入python文件(ctime.py)

复制代码

coding:utf-8

import time

def application(env, start_response):

status = "200 OK"
headers = [("Content-Type", "text/plain")] start_response(status, headers) return time.ctime()

复制代码

运行程序,打开浏览器输入:http://127.0.0.1:8000/ctime.py,显示如下:

每刷新一次就执行相应python代码。

https://www.cnblogs.com/xinyangsdut/p/9099623.html

Python实现简单HTTP服务器的更多相关文章

  1. python 启动简单web服务器

    有时我们在开发web静态页面时,需要一个web服务器来测试. 这时可以利用python提供的web服务器来实现. 1.在命令行下进入某个目录 2.在该目录下运行命令: python -m Simple ...

  2. Python实现简单HTTP服务器(二)

    实现简单web框架 一.框架(MyWeb.py) # coding:utf-8 import time # 设置静态文件根目录 HTML_ROOT_DIR = "./html" c ...

  3. Python SimpleHTTPServer简单HTTP服务器

    搭建FTP,或者是搭建网络文件系统,这些方法都能够实现Linux的目录共享.但是FTP和网络文件系统的功能都过于强大,因此它们都有一些不够方便的地方.比如你想快速共享Linux系统的某个目录给整个项目 ...

  4. 基于python实现简单web服务器

    做web开发的你,真的熟悉web服务器处理机制吗? 分析请求数据 下面是一段原始的请求数据: b'GET / HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nConnectio ...

  5. 用Python实现简单的服务器

    socket接口是实际上是操作系统提供的系统调用.socket的使用并不局限于Python语言,你可以用C或者JAVA来写出同样的socket服务器,而所有语言使用socket的方式都类似(Apach ...

  6. 用Python实现简单的服务器【新手必学】

    如何实现服务器... socket接口是实际上是操作系统提供的系统调用.socket的使用并不局限于Python语言,你可以用C或者JAVA来写出同样的socket服务器,而所有语言使用socket的 ...

  7. Python实现简单HTTP服务器(一)

    一.返回固定内容 # coding:utf-8 import socket from multiprocessing import Process def handle_client(client_s ...

  8. Python实现简单Web服务器

    实验楼教程链接: https://www.shiyanlou.com/courses/552/labs/1867/document http原理详解(http下午茶): https://www.kan ...

  9. python最简单的http服务器

    人生苦短,我用python 今天有个需求就是简单的把自己的图片通过web共享,自然就想起了使用服务器了,在python下使用一个简单的服务器是非常方便的,用到标准库里面的SimpleHTTPServe ...

随机推荐

  1. Django 报错 Reverse for 'content' not found. 'content' is not a valid view function or pattern name.

    Django 报错 Reverse for 'content' not found. 'content' is not a valid view function or pattern name. 我 ...

  2. macOS命令行切换Python版本

    目录 brew安装anaconda3 anaconda3环境变量设置 安装双版本 命令后切换python环境 pip ide vscode set 参考 brew安装anaconda3 brew ca ...

  3. POJ-3468(线段树+区间更新+区间查询)

    A Simple Problem With Integers POJ-3468 这题是区间更新的模板题,也只是区间更新和区间查询和的简单使用. 代码中需要注意的点我都已经标注出来了,容易搞混的就是up ...

  4. Python编程中可能经常用到的函数

    1.os.walk() 一般用法为 import os ph=r'D:\temp\build' for root,dirs,files in os.walk(ph): print(root,dirs, ...

  5. 2019 GDUT Rating Contest II : Problem G. Snow Boots

    题面: G. Snow Boots Input file: standard input Output file: standard output Time limit: 1 second Memory ...

  6. $.ajax data向后台传递参数失败 contentType: "application/json"

    在ajax方法设置中若不添加 contentType: "application/json" 则data可以是对象: $.ajax({ url: actionurl, type: ...

  7. MyBatis的XML配置文件

    属性(properties) 通过properties的子元素设置配置项: <properties> <property name="driver" value= ...

  8. P1208 [USACO1.3]混合牛奶 Mixing Milk(JAVA语言)

    思路 按单价排序然后贪心 题目描述 由于乳制品产业利润很低,所以降低原材料(牛奶)价格就变得十分重要.帮助Marry乳业找到最优的牛奶采购方案. Marry乳业从一些奶农手中采购牛奶,并且每一位奶农为 ...

  9. 软件漏洞--Hello-Shellcode

    软件漏洞--Hello-Shellcode 使用上一次的栈溢出的漏洞软件 可以直接通过栈溢出来修改返回值,或者要跳转的函数地址 实现一个ShellCode来跳转自己的代码 源bug软件代码 #defi ...

  10. Android Studio配置colors.xml

    •colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <! ...