• 全部
  • 互动交流
  • 文章分享

http.server在子进程中运行不正常,请帮忙看看

lj267 2020-12-18 05:20:06
http.server做的httpserver 在主进程中运行正常,放到multiprocessing的子进程中就不能正常运行。查看日志发现卡在self.send_response(200) 这一句。放到子进程中运行是为了方便结束这个进程。以下是代码
#!/usr/bin/env python
#--coding:utf-8--
from multiprocessing import Process
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
from os import path
from urllib.parse import urlparse
import asyncio
import websockets
import logging
import logging.handlers
import datetime
logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)

rf_handler = logging.handlers.TimedRotatingFileHandler('all.log', when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
rf_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))

f_handler = logging.FileHandler('error.log')
f_handler.setLevel(logging.ERROR)
f_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))

logger.addHandler(rf_handler)
logger.addHandler(f_handler)
os.environ['path']=os.environ['path']+';'+os.path.abspath('')

def websocketservice():
# 接收客户端消息并处理,这里只是简单把客户端发来的返回回去
async def recv_msg(websocket):
while True:
recv_text = await websocket.recv()
response_text = f"your submit context: {recv_text}"
await websocket.send(response_text)

# 服务器端主逻辑
# websocket和path是该函数被回调时自动传过来的,不需要自己传
async def main_logic(websocket, path):
await recv_msg(websocket)

# 把ip换成自己本地的ip
start_server = websockets.serve(main_logic, '127.0.0.1', 999)
# 如果要给被回调的main_logic传递自定义参数,可使用以下形式
# 一、修改回调形式
# import functools
# start_server = websockets.serve(functools.partial(main_logic, other_param="test_value"), '10.10.6.91', 5678)
# 修改被回调函数定义,增加相应参数
# async def main_logic(websocket, path, other_param)
print("webserver started")
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

def httpservice():
curdir = path.dirname(path.realpath(__file__))
sep = '/'

# MIME-TYPE
mimedic = [
('.html', 'text/html'),
('.htm', 'text/html'),
('.js', 'application/javascript'),
('.css', 'text/css'),
('.json', 'application/json'),
('.png', 'image/png'),
('.jpg', 'image/jpeg'),
('.gif', 'image/gif'),
('.txt', 'text/plain'),
('.avi', 'video/x-msvideo'),
]

class myHTTPServer_RequestHandler(BaseHTTPRequestHandler):
# GET
def do_GET(self):
sendReply = False
querypath = urlparse(self.path)
filepath, query = querypath.path, querypath.query

if filepath.endswith('/'):
filepath += 'index.html'
filename, fileext = path.splitext(filepath)
for e in mimedic:
if e[0] == fileext:
mimetype = e[1]
sendReply = True
if sendReply == True:
try:
logger.debug(sendReply)
with open(path.realpath(curdir + sep + filepath),'rb') as f:
content = f.read()
logger.debug('0')
self.send_response(200) #这一句过不了,日志只能打印到0,1不能打印出来
logger.debug('1')
self.send_header('Content-type',mimetype)
logger.debug('2')
self.end_headers()
logger.debug('3')
self.wfile.write(content)
logger.debug("4")
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
logger.debug("失败")
port = 8080
print('starting server, port', port)
# Server settings
server_address = ('',port)
httpd = HTTPServer(server_address, myHTTPServer_RequestHandler)
logger.debug('running server...')
httpd.serve_forever()

if __name__ == '__main__':
p1=Process(target=httpservice)
p1.daemon=True
p1.start()
print("进程1")
p2=Process(target=websocketservice)
p2.daemon=True
p2.start()
print("进程2")


...全文
8 点赞 收藏 回复
写回复
回复
切换为时间正序
请发表友善的回复…
发表回复

还没有回复,快来抢沙发~

发帖
脚本语言
创建于2007-08-27

3.7w+

社区成员

JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
申请成为版主
帖子事件
创建了帖子
2020-12-18 05:20
社区公告

CSDN 脚本语言社区接受专栏投稿(专栏会在顶部创建专属你的栏目),投稿需满足以下要求:

  • 脚本语言技术相关;
  • 文章持续更新,保持活跃;
  • 内容清晰明了,干货为主;
  • 文章排版有序,有条有理。

本社区开通招聘专栏,发布招聘信息请联系版主,发布者需要保证招聘信息真实有效,CSDN 平台和版主不对招聘内容负责!

联系方式:私聊版主、发送邮件、QQ联系等均可: