码迷,mamicode.com
首页 > Web开发 > 详细

简单的面向对象-web服务器

时间:2019-08-18 00:25:22      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:port   tar   格式   html_   get   接收   ==   sgi   new   

import socket
import re
import multiprocessing


class WSGIServer(object):
    def __init__(self):
        # 创建套接字
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # 绑定
        self.tcp_server_socket.bind(('', 7890))
        # 监听套接字
        self.tcp_server_socket.listen(128)

    def service_client(self, new_socket):
        # 接收浏览器发送过来的请求
        request = new_socket.recv(1024).decode('utf8')
        request_line = request.splitlines()
        print("")
        print(">" * 20)
        print(request_line)

        file_name = ""
        ret = re.match(r'[^/]+(/[^ ]*)', request_line[0])
        if ret:
            file_name = ret.group(1)
            if file_name == '/':
                file_name = '/index.html'

        # 返回http格式的数据给浏览器
        try:
            f = open('./html' + file_name, 'rb')
        except:
            response = 'HTTP/1.1 404 NOT FOUND\r\n'
            response += '\r\n'
            response += 'file not found!'
            new_socket.send(response.encode('utf8'))
        else:
            html_content = f.read()
            f.close()
            response = 'HTTP/1.1 200 OK\r\n'
            response += '\r\n'
            new_socket.send(response.encode('utf8'))
            new_socket.send(html_content)
        # 关闭连接
        new_socket.close()

    def run(self):
        while True:
            # 等待新客户端的连接
            new_socket, client_addr = self.tcp_server_socket.accept()
            # 为这个客户端服务
            p = multiprocessing.Process(target=self.service_client, args=(new_socket,))
            p.start()
            new_socket.close()
        # 关闭套接字
        self.tcp_server_socket.close()


def main():
    wsgi_server = WSGIServer()
    wsgi_server.run()


if __name__ == '__main__':
    main()

简单的面向对象-web服务器

标签:port   tar   格式   html_   get   接收   ==   sgi   new   

原文地址:https://www.cnblogs.com/dhzg/p/11370945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!