Web服务器-并发服务器-长连接(3.4.4)

@

1.说明

每次new_socket都被强制关闭,造成短连接
所提不要关闭套接字
但是不关闭的话,浏览器不知道发完没有啊
此时用到header的属性Content-Length
http_header += "Content-Length:%d\r\n\r\n" % len(http_body)
将http_body的长度装到返回头,送出给浏览器
当浏览器获取完数据了之后,就不会再加载了

2.代码

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 = "<h1>Sorry not found</h1>".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()

关于作者

个人博客网站
个人GitHub地址
个人公众号:
在这里插入图片描述

posted @ 2019-08-23 14:04  BothSavage  阅读(237)  评论(0编辑  收藏  举报