欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

socket做一个简单的web服务器处理多线程

程序员文章站 2024-03-20 16:31:04
...

重点多线程

import socket


def handle_connection(conn, addr):
    import time
    print("来新的客人了")
    time.sleep(10)
    request = ""
    body = "hello"
    response_params = [
        "HTTP/1.0 200 OK",
        "Content-Type: text/html; charset=utf-8 \r\n",  # 这里一定要\r\n因为http规范 body在\r\n后面
        body,
    ]
    response = "\r\n".join(response_params)
    print(conn.recv(1024))
    conn.send(response.encode())
    conn.close()


def main():
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # serversocket.setblocking(False)
    serversocket.bind(("127.0.0.1", 9001))
    serversocket.listen(10)
    try:
        while True:
            conn, address = serversocket.accept()

            # 建立一个线程并且开始一个线程
            import threading
            t = threading.Thread(target=handle_connection, args=(conn, address))
            t.start()
            # handle_connection(conn, address)
    finally:
        serversocket.close()


if __name__ == '__main__':
    main()

相关标签: 笔记