http_server实例代码

from socket import *

def handleClient(connfd):
    print("-----")
    request = connfd.recv(4096)
    print(request)
    #将request请求按行分割
    request_lines = request.splitlines()
    for line in request_lines:
        print(line.decode())
    
    try:
        f = open("index.html")
    except IOError:
        response = "HTTP/1.1 404 not found\r\n"
        response += "\r\n"
        response += "====Sorry not found====="
    else:
        response = "HTTP/1.1 200 OK\r\n"
        response += "\r\n"
        response += f.read()
    finally:
        #发送给浏览器
        connfd.send(response.encode())

#用来创建套接字
def main():
    sockfd = socket()
    sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    sockfd.bind(("0.0.0.0",8886))
    sockfd.listen(5)
    print("Listen to the port 8888")
    while True:
        connfd,addr = sockfd.accept()
        #处理请求
        handleClient(connfd)
        connfd.close()

if __name__ == "__main__":
    main()

 

posted on 2018-09-07 22:16  zengsf  阅读(158)  评论(0编辑  收藏  举报

导航