[Webserver]miniWebserver-(7)

👉🏻 주요 변경사항은 다음과 같습니다.
The major changes are as follows.

✔️ 멀티 서버 / multi server

— 포트 번호를 바꿔서 여러개의 서버를 동시에 실행 가능합니다.
You can run multiple servers simultaneously by changing the port number.

— Main.cpp

Server server1("127.0.0.1", 5080); 
server1.set_handler([&](const std::string& req) { ... }

Server server2("127.0.0.1", 6080);
server2.set_handler([&](const std::string& req) { ... }

std::thread server_thread(&Server::start, &server1);
std::thread server_thread2(&Server::start, &server2);

server1.stop();
server2.stop();

if (server_thread.joinable()) {
   server_thread.join();
}
if (server_thread2.joinable()) {
   server_thread2.join();
}

✔️ 서버별로 정적파일 서빙 및 라우트 설정 가능합니다.
Static file serving and routing can be configured per server.

— Main.cpp

    Router server1_router("../public1");
    server1_router.add_route("/test1", "test1.html");
    server1_router.add_route("/test2", "test2.html");

    Router server2_router("../public2");
    server2_router.add_route("/test1", "test1.html");
    server2_router.add_route("/test2", "test2.html");

— Router.h

public:
    void add_route(const std::string& path, const std::string& file_name) {
        route_map[path] = file_name;
    }

private:
    std::map<std::string, std::string> route_map;

— Router.cpp

    std::string target_file;

    // 1. 등록된 라우트가 있는지 확인
    // Check if there are registered routes
    if (route_map.count(path)) {
        target_file = route_map[path];
    }
    // 2. 기본 경로("/") 처리
    // Handling default path ("/")
    else if (path == "/") {
        target_file = "index.html";
    }
    // 3. 등록되지 않은 경로는 그냥 경로 이름대로 파일 시도 (또는 404)
    // For unregistered paths, just attempt the file as the path name (or 404)
    else {
        target_file = path;
    }

    std::string full_path = doc_root + "/" + target_file;

✔️ Servre listening 메세지 이후 CMD> 출력하도록 수정했습니다.
Modified to output CMD> after the Servre listening message.

— Main.cpp

std::this_thread::sleep_for(std::chrono::milliseconds(200));

✔️ 디버깅용 메세지는 코멘트 처리 됐습니다.
Debugging messages have been commented out.

👉🏻빌드 / Build

cd build
cmake ..
make

👉🏻 실행 / Run

MacBookAir build % ./main
--- Starting Server Application ---
Server listening on port 5080...
Server listening on port 6080...
CMD> 

👉🏻브라우저 접속 / Access Browser

— 5080과 6080 포트로 두 개의 서버가 실행됩니다.
Two servers are running on ports 5080 and 6080.

— 브라우저에서 각 포트로 접속하면 됩니다.
You can connect to each port in your browser.

http://localhost:5080
http://localhoset:6080

Leave a Reply