[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