欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现静态服务器

程序员文章站 2023-01-22 12:12:30
本文实例为大家分享了python静态服务器的具体代码,供大家参考,具体内容如下 #coding:utf-8 import socket import mult...

本文实例为大家分享了python静态服务器的具体代码,供大家参考,具体内容如下

#coding:utf-8
import socket
import multiprocessing
import re


html_root_dir = "./html"

class httpserver(object):

  #初始化
  def __init__(self):
    self.serversocket = socket.socket(socket.af_inet, socket.sock_stream)
    self.serversocket.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1)


  #开启服务器启动进程
  def start(self):
    self.serversocket.listen(128)
    while true:
      clintsocket, addree = self.serversocket.accept()
      hanlderprogess = multiprocessing.process(target=self.xiexi, args=(clintsocket,))
      hanlderprogess.start()
      clintsocket.close()

  #绑定端口
  def bind(self,port):
    self.serversocket.bind(("", port))


  #获取请求头,进行解析,同时发送相应头
  def xiexi(clserver):
    date = clserver.recv(1024)
    print date
    list = str(date).split("\r\n")
    # 解析
    requesthead = list[0]
    print requesthead
    #使用正则表达式解析出请求头的文件名称
    file = re.match(r"\w+ +(/[^ ]*) ",requesthead).group(1)

    #对获取的问题名判断,如果是/的就进行显示index.html
    if "/"==file:
      file = "/index.html"
    try:
      f = open(html_root_dir+file,"rb")
    except:
      response_start_line = "http/1.1 200 ok \r\n"
      response_headers = "server:my server\r\n"
      response_body = "the file not file"
    else:
      file_date = f.readline()
      f.close()
      response_start_line = "http/1.1 200 ok \r\n"
      response_headers = "server:my server\r\n"
      response_body = file_date.decode("utf-8")

    response = response_start_line+response_headers+"\r\n"+response_body
    print response
    clserver.send(bytes(response))
    clserver.close()

def main():
  server = httpserver()
  server.bind(1001)
  server.start()

if __name__=="__main__":
  main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。