单进程单线程非堵塞方式实现http服务器

#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
# @Time    : 18-7-2 下午6:53
# @Author  : "Fengwr"
# @email   : [email protected]
# @File    : http_单进程_单线程_非堵塞.py
# @Software: PyCharm

import socket
import re

def http_sever(new_socket, recv_data):
    recv_data_list = recv_data.splitlines()
    ret = re.match(r"[^/]+(/[^ ]*)",recv_data_list[0])

    file_name = ""
    if ret:
        file_name = ret.group(1)
        if file_name == "/":
            file_name = "/index.html"

    http_header = ""
    http_body = ""

    try:
        f = open("./html" + file_name, "rb")
    except:
        http_body = "

Sorry not found

".encode("utf-8") http_header = "HTTP/1.1 404 NOT FOUND\r\n" http_header += "Content-Length:%d\r\n\r\n" % len(http_body) else: http_body = f.read() f.close() http_header = "HTTP/1.1 200 OK\r\n" http_header += "Content-Length:%d\r\n\r\n" % len(http_body) new_socket.send(http_header.encode("utf-8")) new_socket.send(http_body) def main(): tcp_sever_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_sever_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcp_sever_socket.bind(("",7890)) tcp_sever_socket.listen(128) # 设置非堵塞 tcp_sever_socket.setblocking(False) client_lists = list() while True: try: new_socket, new_add = tcp_sever_socket.accept() except Exception as ret: pass else: # 设置非堵塞 new_socket.setblocking(False) client_lists.append(new_socket) for client_socket in client_lists: try: # 尝试接收数据 recv_data = client_socket.recv(1024).decode("utf-8") except Exception as f: # 如果没有数据 pass else: # 如果有数据有两种情况,1,客户端发来了数据,2客服端下线 if recv_data: http_sever(client_socket, recv_data) else: client_socket.close() client_lists.remove(client_socket) tcp_sever_socket.close() if __name__ == '__main__': main()

新知识点:socket.setbloking(False)  # 将套接字设置为非堵塞的方式。 Content-Length:%d % len(http_body)  # 告诉客户端要发送的body内容的长度,实现长链接发送。


你可能感兴趣的:(python_http)