手写走通HTTP server 第二版本

HTTP server 2.0

  1 接收客户请求

  2 解析客户端请求

  3 组合数据,形成HTTP response

  4 将数据发送给客户端

升级 :

  1 多线程接收客户端请求

  2 基本的请求解析,根据请求返回数据(相应内容)

  3 除了可以请求静态网页,也可以请求简单的数据

  4 将功能封装在一个类中

#coding = utf-8
'''http 2.0
1多线程并发
2可以请求简单数据
3能进行简单请求解析
4结构使用类进行封装
'''
import socket, os, sys, traceback
from threading import Thread

#封装具体的服务器功能
class HTTPserver(object):
    def __init__(self,server_addr,server_static_dir):
            self.server_addr = server_addr
            self.server_static_dir = server_static_dir
            self.ip = server_addr[0]
            self.port = server_addr[1]
            self.create_socket()

    def create_socket(self):#创建
        self.sockfd = socket.socket()
        self.sockfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sockfd.bind(self.server_addr)

    def serve_forever(self):#启动
        self.sockfd.listen()
        print('listen the prot:%s' % self.port)
        while True:
            try:
                confd, addr = self.sockfd.accept()
            except KeyboardInterrupt:
                self.sockfd.close()
                sys.exit('服务器退出')
            except Exception:
                traceback.print_exc()
                continue
            # 创建新的线程处理请求
            t = Thread(target=self.handle, args=(confd,))
            t.Daemon = True
            t.start()

    def handle(self, confd):
        # 接收客户端请求
        data = confd.recv(1024)

        # 解析请求内容
        dataHeader = data.splitlines()

        # 获取具体请求内容
        getRequest = str(dataHeader[0]).split(' ')[1]
        urls = ['/','/index','/index_1','/index_2']
        if getRequest == '/' or getRequest[-5:] == '.html':#获取主页
            print('已进行来')
            self.get_html(confd)
        elif getRequest in urls:  #获取下级页面
            self.get_data(confd,getRequest)
        else:
            self.error_(confd)
        confd.close()

    def get_data(self, confd,getReques):#获取页面数据
        getReques = getReques.split('/')[1]
        path =os.path.join(self.server_static_dir,getReques)
        print(path)
        with open(path+'.html','r') as f:
            data = f.read()
        response = 'HTTP/1.1 200 OK\r\n'
        response +='\r\n'
        response +=data
        confd.send(response.encode())

    def error_(self,confd):#出错处理
        response = 'HTTP/1.1 404 NOT FUOUND\r\n'
        response += '\r\n'
        responseBOdy = 'SORRY,NOT PAGE'
        response += responseBOdy
        confd.send(responseBOdy.encode())

    def get_html(self,confd):#首页处理
        with open('index.html','r') as f:
            data = f.read()
        #print(data)
        xieyi = 'HTTP/1.1 200 OK \r\n'
        xieyi += '\r\n'
        xieyi += data
        confd.send(xieyi.encode())

if __name__ == '__main__':
    server_addr = ('127.0.0.1', 8080)#地址
    server_static_dir = os.getcwd()#静态页面目录

    #生成对象
    httpd = HTTPserver(server_addr, server_static_dir)

    #启动服务器
    httpd.serve_forever()





 

posted @ 2018-09-17 16:25  Sky__liu  阅读(150)  评论(0编辑  收藏  举报