Web服务器-服务器开发-返回固定页面的HTTP服务器(3.3.1)

@

1.注意

浏览器解析的时候偶\r\n才算一个换行符
发送的str要编码,这里使用的是utf8
其他的都和上一篇没有什么区别
这里主要返回的是固定的网址

2.代码

from socket import *

def service_client(new_socket):
    '''为这个客户端返回数据'''

    # 1.接收浏览器发送过来的请求,即http请求
    #GET /HTTP/1.1
    # ...
    request = new_socket.recv(1024)

    #2,返回http格式的数据给浏览器
    #2.1准备发送给浏览器的数据 ---header
    response = "HTTP/1.1 200 OK\r\n"#正常浏览器\r\n代表的是换行
    response += "\r\n"
    #2.2准备发送给浏览器的数据
    response += "hahaha"
    new_socket.send(response.encode("utf-8"))

    #3.关闭套接字
    new_socket.close()


def main():
    '''用来完成整体的控制'''
    #1.创建套接字
    tcp_server_socket = socket(AF_INET, SOCK_STREAM)

    # 2.绑定本地信息
    port = 7891
    address = ('', port)
    tcp_server_socket.bind(address)

    # 3.变为监听,将主动套接字变为被动套接字
    tcp_server_socket.listen(128)

    #等待连接
    while True:
        client_socket, clientAddr = tcp_server_socket.accept()
        # 接收对方发送过来的数据
        service_client(client_socket)


    # 关闭监听套接字
    tcp_server_socket.close()


if __name__ == "__main__":
    main()

关于作者

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

猜你喜欢

转载自www.cnblogs.com/simon-idea/p/11399234.html