用socket进行网络通信

建立tcp传输

    serves_socket = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
    serves_socket.bind(("",8000))
    serves_socket.listen(128)

建立多线程访问

while True:
        cli_socket, cli_address = serves_socket.accept()
        print("[%s %s]客户连接上了"% cli_address)
        handale_client_socket = Process(target=handle_client,args=(cli_socket,))
        handale_client_socket.start()
        cli_socket.close()

处理客户端请求以及生成HTTP报头

def handle_client(cli_socket):
    '''处理客户端请求'''
    # 获取客户端请求数据
    request_data = cli_socket.recv(1024)
    print(request_data)

    #构造响应数据
    reponse_start_line = "HTTP/1.1 200 ok\r\n"
    reponse_headers = "Server: myserves\r\n"
    reponse_body = "hello world"
    reponse = reponse_start_line+reponse_headers+"\r\n"+reponse_body
    print(reponse)

    #向客户端返回响应数据
    cli_socket.send(bytes(reponse,"utf-8"))

    #关闭客户端连接
    cli_socket.close()

一个简单的链接搭建完成了 访问http://127.0.0.2:8000/ 结果:

hello world

访问静态文件

  • 进行同一个接口重复访问设置
  serves_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
  • 对2进制文件进行utf-8解码
#解析报文   GET / HTTP/1.1
    request_lines = request_data.splitlines()
    request_start_line = request_lines[0]
    file_name = re.match(r'\w+ +(/[^ ]*)',request_start_line.decode("utf-8")).group(1)
    if "/"==file_name:
        file_name="/index.html"
    try:
        with open(HTML_ROOT_DIR + file_name,"rb") as f:
            file_data = f.read()
    except IOError:
        reponse_start_line = "HTTP/1.1 404 Not Found\r\n"
        reponse_headers = "Server: myserves\r\n"
        reponse_body = "文件找不到"
    else:
    #构造响应数据
        reponse_start_line = "HTTP/1.1 200 ok\r\n"
        reponse_headers = "Server: myserves\r\n"
        reponse_body = file_data.decode("utf-8")
    reponse = reponse_start_line+reponse_headers+"\r\n"+reponse_body
    print(reponse)

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券