Based HTTP server

[Http-based server]

  1. HTTP request is received
  2. Given a certain response
# http_server.py
# 基础的http服务器
# 1.接收HTTP请求
# 2.给出一定的响应
# 在浏览器输入本机ip:端口号即可访问index.html

from socket import *

# 处理客户请求,返回响应
def handleClient(connfd):
    # 接收消息
    request = connfd.recv(4096)
    # print('***********')
    # print(request)
    # print('***********')
    requestHeadlers = request.splitlines()
    # splitlines()按行进行分割
    for line in requestHeadlers:
        print(line)
    # 发送消息
    try:
        f = open('index2.html','r')
    except IOError:
        # 添加响应行
        response = 'HTTP/1.1 404 not found\r\n'
        # 添加响应体
        response += '\r\n'
        # 空行
        response += '===网页没找到==='
        # 响应体
    else:
        response = 'HTTP/1.1 200 OK\r\n'
        response += '\r\n'
        for i in f:
            response += i

    finally:
        connfd.send(response.encode())
# 基础配置,功能函数的调用
def main():
    # 创建套接字
    sockfd = socket(AF_INET,SOCK_STREAM)
    sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    # 绑定
    sockfd.bind(('0.0.0.0',8000))
    # 监听
    sockfd.listen(10)
    while True:
        # 此循环示意当一个客户端断开时,下一个客户端可以继续访问
        print('Listen to the port 8000......')
        # 阻塞等待客户端请求
        connfd,addr = sockfd.accept()
        # 处理请求
        handleClient(connfd)
        connfd.close()




if __name__ == '__main__':
    main()
Published 85 original articles · won praise 2 · Views 5010

Guess you like

Origin blog.csdn.net/zhangxuelong461/article/details/104058852