python socket超简单web服务器

python socket超简单web服务器

此案列只支持像这种“127.0.0.1/hello.html”同级目录

import socket

class myserver():


    #初始化内容
    def __init__(self,add,port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        s.bind((add,port))
        s.listen(2)
        self.s = s


    #一且的开始
    def start(self):
        while True:
            self.sock , add = self.s.accept()
            data = self.sock.recv(1024)
            if not data:
                break
            #解码
            data = data.decode()
            #查找路径
            data = self.Division(data)
            #判断是否按照路径打开页面  相等则打开默认
            if data == ['GET', 'HTTP', '1.1']:
                send_data = self.send_data(' Welcome ')
                self.sock.send(send_data)
                self.sock.close()
            else:
                #带入查找文件
                data = self.find_file(data[1])
                send_data = self.send_data(data)
                self.sock.send(send_data)
                self.sock.close()

    def find_file(self,data):
        try:
            with open(data,'r') as f:
                file = f.read()
            return file
        except EnvironmentError as e:
            return str(e)

    # 查找路径
    def Division(self,data):
        index = data.index('\r\n')
        data = data[:index]
        data = data.replace('/', ' ')
        data = data.split()
        return data


    #发送信息
    def send_data(self,data):
        response_line = 'HTTP/1.1 200 OK\r\n'
        response_head = 'server: fistserver 1.0\r\n'
        response_blank = '\r\n'
        response_body = data
        response_send = (response_line + response_head + response_blank + response_body).encode()
        return response_send
if __name__ == '__main__':
    server = myserver('127.0.0.1',8888)
    server.start()

你可能感兴趣的:(python,服务器)