Python - 静态web服务-多任务

import socket
import threading


def handle(user_socket):
    web_recv = user_socket.recv(4096)
    if len(web_recv) == 0:
        print('放弃连接')
        user_socket.close()
        return
    web_request = web_recv.decode()
    index = web_request.split(' ', 2)
    request_path = index[1]
    if request_path == '/':
        request_path = '/index.html'
    try:
        with open('.' + request_path, mode='rb') as f:
            file_data = f.read()
    except Exception as e:
        print(e)
        with open('./error.html', mode='rb') as f:
            error_file = f.read()
        response_line = 'HTTP/1.1 404 Not Found\r\n'
        response_head = 'PWS2023\r\n'
        response = ((response_line + response_head + '\r\n').encode()
                    + error_file)
        user_socket.send(response)
    else:
        response_line = 'HTTP/1.1 200 OK\r\n'
        response_head = 'PWS2023\r\n'
        response = ((response_line + response_head + '\r\n').encode()
                    + file_data)
        user_socket.send(response)
    finally:
        user_socket.close()


if __name__ == '__main__':
    def main():
        main_socket = socket.socket(socket.AF_INET,
                                    socket.SOCK_STREAM)
        main_socket.bind(('', 8000))
        main_socket.listen(128)
        while True:
            user_socket, ip_port = main_socket.accept()
            print(ip_port)
            sub_thread = threading.Thread(target=handle,
                                          args=(user_socket,))
            sub_thread.setDaemon(True)
            sub_thread.start()

    main()

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值