Discuss / Python / http静态服务器

http静态服务器

Topic source

Aspire

#1 Created at ... [Delete] [Delete and Lock User]
import os.path
import socket
import threading
import sys




class httpServer(object):
    def __init__(self, prot):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.server_socket.bind(("", prot))
        self.server_socket.listen(128)

    def recvHander(self, sock):

        try:
            res = sock.recv(1024*4)
            # 接收到请求
            if len(res) == 0:
                return sock.close()

            path = res.decode('utf-8').split(' ', maxsplit=2)[1]
            if path == '/':
                path = '/index.html'

            filePath = ['static/' , path]
            if not os.path.exists(''.join(filePath)):
                filePath[1] = '404.html'

            with open(''.join(filePath), 'rb') as file:
                content = file.read()

            txt = 'HTTP/1.1 200\r\n'
            txt += 'Server: MyServer\r\n'
            txt += 'Content-Type: *; charset=UTF-8\r\n'
            txt += '\r\n'
            txt = txt.encode('utf-8')
            txt += content

            sock.send(txt)
        except Exception as e:
            print(e)
        finally:
            sock.close()

    def start(self):
        while True:
            # 接收一个链接
            sock, addr = self.server_socket.accept()
            threading.Thread(target= self.recvHander, args=(sock,), daemon=True).start()


if __name__ == '__main__':
    prot = 8089
    if len(sys.argv)==2:
        prot = int(sys.argv[1])
    http = httpServer(prot)
    http.start()

  • 1

Reply