美文网首页
使用多进程完成HTTP服务器

使用多进程完成HTTP服务器

作者: BJ000 | 来源:发表于2019-11-19 08:44 被阅读0次

import socket

import re

import multiprocessing

def service_client(new_socket):

  """用来完成整体的控制"""

  #1、接收浏览器发送过来的请求,即http请求

  #GET /index.html HTTP/1.1

#.....

  request= new_socket.recv(1024).decode("utf-8")

# print(">>>" *20)

# print (request)

# 切割,切割完变成列表

  request_lines= request.splitlines()

print("")

print(">>>" *30)

print(request_lines)

#get post put del...  请求方式

  # 匹配只要不是/ +表示一个到多个

  ret= re.match(r"[^/]+(/[^ ])*", request_lines[0])

file_name= ""

  if ret:

    file_name= ret.group(1)#取第一个括号的东西

    print("*" * 50, file_name)

if file_name== '/':

      file_name= '/index.html'

  #2、返回http格式的数据给浏览器

  try:

    # f = open("../../FrontCode-master/buickmall/index.html", 'rb')  #rb二进制

    f= open("../../FrontCode-master/buickmall" + file_name,'rb')

except:

    response= "HTTP/1.1 404 NOT FOUND\r\n"  # \r\n兼容Windows浏览器的换行

    response+= "\r\n"

    response+= "---file not found---"

    new_socket.send(response.encode("utf-8"))

else:

    html_content= f.read()#read读取

    f.close()#关闭

    # 2.1 准备发送给浏览器的数据:header

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

    response+= "\r\n"

    # 2.2准备发送给浏览器的数据:Body

# response += "

hahaha

"

  #将response header发送给浏览器

  new_socket.send(response.encode("utf-8"))

# 将response Body发送给浏览器

  new_socket.send(html_content)

# 关闭套接字

  new_socket.close()

def main():

  """用来完成整体的控制"""

  # 1、创建套接字

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

# 2、绑定

  tcp_server_socket.bind(("",5051))#2580端口,不能重复

  # 3、变为监听套接字

  tcp_server_socket.listen(128)#最大128人同时链接

  while True:

    # 4、等待新客户去哪的链接

    new_socket, client_addr= tcp_server_socket.accept()

# 5、为这个客户端服务

    p= multiprocessing.Process(target=service_client,args=(new_socket,))

p.start()

new_socket.close()

#6、关闭监听套接字

  tcp_server_socket.close()

if __name__== '__main__':

  main()

相关文章

  • 关于服务器运行的一些小代码

    根据用户的需求返回相应的代码 使用多进程完成http服务器 使用多线程完成http服务器 使用gevent来实现h...

  • 使用多进程完成HTTP服务器

    import socket import re import multiprocessing def servic...

  • 03-web服务器v3.1--03

    多进程、多线程实现Http服务器 使用gevent实现Http服务器开启多任务 单进程、线程、非堵塞实现并发 长链...

  • 根据PV或者QPS来计算需要多少台机器

    QPS单个进程每秒请求服务器成功的次数req/sec = 总请求数 /(进程总数 * 请求时间)一般使用http_...

  • Python 开发web服务器,多线程

    仅供学习参考,转载请注明出处 前面介绍了使用进程的方式来优化处理http请求 Python 开发web服务器,多进...

  • nodeJS内置模块

    1、http模块 创建服务器 使用 http.createServer() 方法创建服务器,并使用 listen ...

  • 自我学习Node学习记录

    开启HTTP服务器 开启HTTP服务器 如何使用curl 如何使用curl Node如何使用路由形式 Node如何...

  • 处理kdevtmpfsi病毒

    服务器CPU占用100%,导致http请求无法进行top命令查看进程占用,发现kdevtmpfsi进程占用95%甚...

  • 图解HTTP笔记——第一章

    1.1 使用HTTP协议访问Web Web使用一种名为HTTP的协议作为规范,完成从客户端到服务器等一系列运作流程...

  • 理解HTTP

    1.使用HTTP访问web应用 web使用一种http(超文本传输协议)的协议作为规范完成从客户端到服务器等一系列...

网友评论

      本文标题:使用多进程完成HTTP服务器

      本文链接:https://www.haomeiwen.com/subject/ifaiictx.html