Python Web靜態(tài)服務(wù)器非堵塞模式實(shí)現(xiàn)方法示例
本文實(shí)例講述了Python Web靜態(tài)服務(wù)器非堵塞模式實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
單進(jìn)程非堵塞 模型
#coding=utf-8
from socket import *
import time
# 用來存儲(chǔ)所有的新鏈接的socket
g_socket_list = list()
def main():
server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR , 1)
server_socket.bind(('', 7890))
server_socket.listen(128)
# 將套接字設(shè)置為非堵塞
# 設(shè)置為非堵塞后,如果accept時(shí),恰巧沒有客戶端connect,那么accept會(huì)
# 產(chǎn)生一個(gè)異常,所以需要try來進(jìn)行處理
server_socket.setblocking(False)
while True:
# 用來測(cè)試
time.sleep(0.5)
try:
newClientInfo = server_socket.accept()
except Exception as result:
pass
else:
print("一個(gè)新的客戶端到來:%s" % str(newClientInfo))
newClientInfo[0].setblocking(False) # 設(shè)置為非堵塞
g_socket_list.append(newClientInfo)
for client_socket, client_addr in g_socket_list:
try:
recvData = client_socket.recv(1024)
if recvData:
print('recv[%s]:%s' % (str(client_addr), recvData))
else:
print('[%s]客戶端已經(jīng)關(guān)閉' % str(client_addr))
client_socket.close()
g_socket_list.remove((client_socket,client_addr))
except Exception as result:
pass
print(g_socket_list) # for test
if __name__ == '__main__':
main()
web靜態(tài)服務(wù)器-單進(jìn)程非堵塞
import time
import socket
import sys
import re
class WSGIServer(object):
"""定義一個(gè)WSGI服務(wù)器的類"""
def __init__(self, port, documents_root):
# 1. 創(chuàng)建套接字
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2. 綁定本地信息
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind(("", port))
# 3. 變?yōu)楸O(jiān)聽套接字
self.server_socket.listen(128)
self.server_socket.setblocking(False)
self.client_socket_list = list()
self.documents_root = documents_root
def run_forever(self):
"""運(yùn)行服務(wù)器"""
# 等待對(duì)方鏈接
while True:
# time.sleep(0.5) # for test
try:
new_socket, new_addr = self.server_socket.accept()
except Exception as ret:
print("-----1----", ret) # for test
else:
new_socket.setblocking(False)
self.client_socket_list.append(new_socket)
for client_socket in self.client_socket_list:
try:
request = client_socket.recv(1024).decode('utf-8')
except Exception as ret:
print("------2----", ret) # for test
else:
if request:
self.deal_with_request(request, client_socket)
else:
client_socket.close()
self.client_socket_list.remove(client_socket)
print(self.client_socket_list)
def deal_with_request(self, request, client_socket):
"""為這個(gè)瀏覽器服務(wù)器"""
if not request:
return
request_lines = request.splitlines()
for i, line in enumerate(request_lines):
print(i, line)
# 提取請(qǐng)求的文件(index.html)
# GET /a/b/c/d/e/index.html HTTP/1.1
ret = re.match(r"([^/]*)([^ ]+)", request_lines[0])
if ret:
print("正則提取數(shù)據(jù):", ret.group(1))
print("正則提取數(shù)據(jù):", ret.group(2))
file_name = ret.group(2)
if file_name == "/":
file_name = "/index.html"
# 讀取文件數(shù)據(jù)
try:
f = open(self.documents_root+file_name, "rb")
except:
response_body = "file not found, 請(qǐng)輸入正確的url"
response_header = "HTTP/1.1 404 not found\r\n"
response_header += "Content-Type: text/html; charset=utf-8\r\n"
response_header += "Content-Length: %d\r\n" % (len(response_body))
response_header += "\r\n"
# 將header返回給瀏覽器
client_socket.send(response_header.encode('utf-8'))
# 將body返回給瀏覽器
client_socket.send(response_body.encode("utf-8"))
else:
content = f.read()
f.close()
response_body = content
response_header = "HTTP/1.1 200 OK\r\n"
response_header += "Content-Length: %d\r\n" % (len(response_body))
response_header += "\r\n"
# 將header返回給瀏覽器
client_socket.send( response_header.encode('utf-8') + response_body)
# 設(shè)置服務(wù)器服務(wù)靜態(tài)資源時(shí)的路徑
DOCUMENTS_ROOT = "./html"
def main():
"""控制web服務(wù)器整體"""
# python3 xxxx.py 7890
if len(sys.argv) == 2:
port = sys.argv[1]
if port.isdigit():
port = int(port)
else:
print("運(yùn)行方式如: python3 xxx.py 7890")
return
print("http服務(wù)器使用的port:%s" % port)
http_server = WSGIServer(port, DOCUMENTS_ROOT)
http_server.run_forever()
if __name__ == "__main__":
main()
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- Python Tornado實(shí)現(xiàn)WEB服務(wù)器Socket服務(wù)器共存并實(shí)現(xiàn)交互的方法
- python3實(shí)現(xiàn)微型的web服務(wù)器
- Python面向?qū)ο笾甒eb靜態(tài)服務(wù)器
- python實(shí)現(xiàn)靜態(tài)web服務(wù)器
- Tornado Web Server框架編寫簡(jiǎn)易Python服務(wù)器
- Python Web程序部署到Ubuntu服務(wù)器上的方法
- python快速建立超簡(jiǎn)單的web服務(wù)器的實(shí)現(xiàn)方法
- Python實(shí)現(xiàn)簡(jiǎn)易版的Web服務(wù)器(推薦)
- python探索之BaseHTTPServer-實(shí)現(xiàn)Web服務(wù)器介紹
- Python 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的web服務(wù)器
相關(guān)文章
Python實(shí)現(xiàn)復(fù)制文檔數(shù)據(jù)
我們百度搜索一些東西得時(shí)候,經(jīng)常找到文檔里面然后就會(huì)發(fā)現(xiàn)需要充值才能復(fù)制!怎么可以不花錢也保存呢?今天就分享給大家一個(gè)python獲取文檔數(shù)據(jù)得方法,需要的可以收藏一下2022-12-12
Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法
下面小編就為大家分享一篇Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Django給表單添加honeypot驗(yàn)證增加安全性
這篇文章主要介紹了Django給表單添加honeypot驗(yàn)證增加安全性的方法,幫助大家更好的理解和學(xué)習(xí)使用Django框架,感興趣的朋友可以了解下2021-05-05

