Python:单线程HTTP服务端_方法封装版

最简单最原始的HTTP版本.

已经去掉注释,如果需要注释我上传注释版.

import socket,re,time


def open_file(路径):
    try:
        client_html_data=open('python_demo/HTTP协议/'+路径,'rb')
    except Exception as  ret:   
        return '404错误 页面不存在,请重新输入地址'.encode('gbk')
    else: 
        html_read_data=client_html_data.read()
        client_html_data.close()
        return html_read_data


def service_client(client_socket,recv_data):
    print('客户端发送的请求内容:')
    print('-'*50)
    print(recv_data)
    print('-'*50)
    ret_filename_=re.search(r'\w+\.html|favicon.ico',recv_data) 
    if ret_filename_: 
        file_name=ret_filename_.group()
        file_data=open_file(file_name) 
        html_header='HTTP/1.1 200 OK\r\n'   
        html_header+='Content-length:%d\r\n\r\n'%len(file_data) 
        client_socket.send(html_header.encode('gbk'))
        client_socket.send(file_data) 
    else: 
        file_data=open_file('index.html')   
        html_header='HTTP/1.1 200 OK\r\n'   
        html_header+='Content-length:%d\r\n\r\n'%len(file_data) 
        client_socket.send(html_header.encode('gbk'))
        client_socket.send(file_data) 


def main():
    ''' 主线程 '''
    tcp_socket_sever=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcp_socket_sever.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)      
    tcp_socket_sever.bind(('127.0.0.1',8001))
    tcp_socket_sever.listen(128)
    tcp_socket_sever.setblocking(False) 
    print('服务端已运行---------------------------------------')
    client_socket_list=list()
    while True:
        time.sleep(1)
        try:
            new_client_socket,clientAddr=tcp_socket_sever.accept() 
        except Exception as ret:  
            print('客户端链接个数:',len(client_socket_list))
            print('等待新客户端链接------------')
        else: 
            new_client_socket.setblocking(False) 
            client_socket_list.append(new_client_socket) 
        for client_socket in client_socket_list:  
            try:
                recv_data=client_socket.recv(10240).decode('gbk') 
            except Exception as  ret:   
                print('列表中对象有: ',client_socket)
            else: 
                if recv_data : 
                    service_client(client_socket,recv_data) 
                else: 
                    client_socket_list.remove(client_socket)
                    client_socket.close()
    tcp_socket_sever.close() 


if __name__ == '__main__':
    main()

 

你可能感兴趣的:(python基础版)