[Webserver]miniWebserver (5)

๐Ÿ‘‰๐Ÿป ์ฃผ์š” ๋ณ€๊ฒฝ์‚ฌํ•ญ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.
The major changes are as follows.

โœ”๏ธ ๊ธฐ์กด์˜ ์ปค๋งจ๋“œ ์ข…๋ฃŒ ๋ถ€๋ถ„์„ ํ•จ์ˆ˜๋กœ ๋ณ€๊ฒฝํ–ˆ์Šต๋‹ˆ๋‹ค.(main.cpp)
I changed the existing command termination part to a function. (main.cpp)

 my_server.run_cmd();

โœ”๏ธ ๋ผ์šฐํ„ฐ ์„ค์ • ํŒŒ์ผ์„ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค.
I added the router configuration file.

Router.h Router.cpp

โœ”๏ธ ๋ผ์šฐํ„ฐ์— ๋งˆ์ž„ํƒ€์ž…์„ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค.(์•„์ง์€ body๋งŒ ๋ฆฌํ„ด)
Added MIME types to the router. (Currently only returns body)

๐Ÿ‘‰๐Ÿป ๊ธฐ์กด ์ฝ”๋“œ์—์„œ ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ๋ณ€๊ฒฝ๋œ ๋ถ€๋ถ„์€ โ—๏ธ๋กœ ํ‘œ์‹œ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.
Parts added or changed from the existing code are marked with โ—๏ธ.

๐Ÿ‘‰๐Ÿป ๋‚˜๋จธ์ง€ ์„ค๋ช…์€ ์ฝ”๋“œ ์ฃผ์„์„ ์ฐธ๊ณ ํ•˜์„ธ์š”
Please refer to the code comments for the rest of the explanation.

๐Ÿ‘‰๐Ÿป ์ฝ”๋“œ / Code

โœ”๏ธ Main.cpp

#include "Server.h" // ์†Œ์ผ“์„œ๋ฒ„/Scoket Server
#include "Router.h" // ๋ผ์šฐํ„ฐ/routerโ—๏ธ
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <string>
#include <map>
#include <utility> // std::pair ์‚ฌ์šฉ์„ ์œ„ํ•ด ์ถ”๊ฐ€ / Added for using std::pair โ—๏ธ


int main() {
    Server my_server("127.0.0.1", 5080);
    Router my_router; // ๋ผ์šฐํ„ฐ ์ธ์Šคํ„ด์Šค / router instance โ—๏ธ

    // ํ•ธ๋“ค๋Ÿฌ ์„ค์ • - ๋งˆ์ž„ํƒ€์ž…์ ์šฉ โ—๏ธ
    // Handler Settings - Apply Mime Type
    my_server.set_handler([&](const std::string& req) {
        auto [mime, body] = my_router.router(req);
        // ์—ฌ๊ธฐ์„œ mime๋„ ๊ฐ™์ด ๋„˜๊ฒจ์ค˜์•ผ ํ•˜์ง€๋งŒ, ํ˜„์žฌ๋Š” body๋งŒ ๋ฆฌํ„ดํ•˜๋Š” ๊ตฌ์กฐ์ž…๋‹ˆ๋‹ค.
        // Although the mime should also be passed here, the current structure only returns the body.
        return body;
    });

    // 3. ์„œ๋ฒ„ ์—”์ง„ ์‹œ์ž‘ (์Šค๋ ˆ๋“œ) / Start server engine (thread)
    std::thread server_thread(&Server::start, &my_server);
    std::cout << "--- Starting Server Application ---" << std::endl;

    // 4. ์ปค๋งจ๋“œ ์ž…๋ ฅ ๋ฃจํ”„ (์Šค๋ ˆ๋“œ๋กœ ๋Œ๋ฆฌ์ง€ ๋ง๊ณ  ๋ฉ”์ธ์—์„œ ์ง์ ‘ ์‹คํ–‰) โ—๏ธ
    // ๋ฉ”์ธ ์Šค๋ ˆ๋“œ๊ฐ€ ์—ฌ๊ธฐ์„œ ์ž…๋ ฅ์„ ๋Œ€๊ธฐํ•˜๋ฏ€๋กœ ํ”„๋กœ๊ทธ๋žจ์ด ๋ฐ”๋กœ ์ข…๋ฃŒ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

    // 4. Command Input Loop (Do not run as a thread, execute directly in Main)
    // The main thread waits for input here, so the program does not terminate immediately.
    my_server.run_cmd();

    // 5. run_cmd()๋ฅผ ๋น ์ ธ๋‚˜์™”๋‹ค๋Š” ๊ฒƒ์€ ์‚ฌ์šฉ์ž๊ฐ€ exit๋ฅผ ์ณค๋‹ค๋Š” ๋œป์ด๋ฏ€๋กœ ์ •๋ฆฌ ์‹œ์ž‘
    // 5. Exiting run_cmd() means the user typed exit, so start cleaning up.
    my_server.stop();

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

    std::cout << "[MAIN] Server Application Finished." << std::endl;
    return 0;
}

โœ”๏ธ Server.h

#include <string>
#include <atomic>
#include <functional>

class Server {
public:
    // ์ƒ์„ฑ์ž: ์„œ๋ฒ„ ์ดˆ๊ธฐํ™” (IP, Port)
    // Constructor: Initialize server (IP, Port)
    Server(const std::string& ip, int port);

    // ์†Œ๋ฉธ์ž / Destructor
    ~Server() {
        stop();
    }

    // ์„œ๋ฒ„ ์†Œ์ผ“ ํŒŒ์ผ ๋””์Šคํฌ๋ฆฝํ„ฐ๋ฅผ ์ €์žฅํ•  ๋ฉค๋ฒ„ ๋ณ€์ˆ˜
    // Member variable to store server socket file descriptors
    int server_fd = -1;

    // ์„œ๋ฒ„ ์‹คํ–‰ ํ•จ์ˆ˜: ๋ฆฌ์Šค๋‹์„ ์‹œ์ž‘ํ•˜๊ณ  ๋ฉ”์ธ ๋ฃจํ”„๋ฅผ ๋Œ๋ฆผ
    // Server execution function: Starts listening and runs the main loop
    bool start();

    // ์„œ๋ฒ„ ์ข…๋ฃŒ / Server close(ํ•„์š”ํ•˜๋‹ค๋ฉด / if neccessary)
    // Shut down the server (if necessary)
    void stop();

    // ์ปค๋งจ๋“œ ๋กœ์ง ๊ตฌํ˜„ / implement command loginโ—๏ธ
    void run_cmd();

    // -- ๋ธŒ๋ผ์šฐ์ € ๋ฉ”์„ธ์ง€ ๋ฐ”๊พธ๊ธฐ / Change browser message --
    // string(์š”์ฒญ)์„ ๋ฐ›์•„์„œ string(์‘๋‹ต๋‚ด์šฉ)์„ ๋ฑ‰๋Š” ํ•จ์ˆ˜๋ฅผ ๋‹ด๋Š” ๊ทธ๋ฆ‡
    // A container for a function that takes a string (request) and returns a string (response content)
    std::function<std::string(const std::string&)> logic_handler;

    // main์—์„œ ๋žŒ๋‹ค๋ฅผ ๋„ฃ์–ด์ค„ ํ•จ์ˆ˜(Main.cpp์—์„œ์‚ฌ์šฉ)
    // Function to pass the lambda in main (used in Main.cpp)
    void set_handler(std::function<std::string(const std::string&)> handler) {
        logic_handler = handler;
    }

    void handle_client_test(int client_socket);


private:
    std::string ip_address;
    int port_number;

    // ์„œ๋ฒ„๊ฐ€ ์‹คํ–‰ ์ƒํƒœ์ธ์ง€ ํ™•์ธํ•˜๋Š” ํ”Œ๋ž˜๊ทธ
    // Flag to check if the server is running
    std::atomic<bool> running{false};

    // ์‹ค์ œ ๋ฆฌ์Šค๋‹ ๋ฐ ์—ฐ๊ฒฐ ์ˆ˜์‹  ๋กœ์ง (๋‚ด๋ถ€ ๊ตฌํ˜„)
    // Actual listening and connection reception logic (internal implementation)
    void run_listener();

    // ์—ฐ๊ฒฐ ์ฒ˜๋ฆฌ ๋กœ์ง (์Šค๋ ˆ๋“œ ํ’€ ๋˜๋Š” ๋ณ„๋„ ํ•ธ๋“ค๋Ÿฌ์—๊ฒŒ ์œ„์ž„)
    // Connection handling logic (delegated to thread pool or separate handler)
    void handle_client(int client_socket);

};

โœ”๏ธServer.cpp

#include "Server.h"
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <thread>
#include <vector>
#include <functional> // ์ถ”๊ฐ€ / add

#define BACKLOG 10 // ๋Œ€๊ธฐ ํ ํฌ๊ธฐ / wait queue size

Server::Server(const std::string& ip, int port)
    : ip_address(ip), port_number(port) {}

void Server::run_listener() {
    //std::cout << "[INFO] Server listening on " << ip_address << ":" << port_number << std::endl;

    // --- 1. ์†Œ์ผ“ ์ƒ์„ฑ / Socket Creation --- //

    server_fd = socket(AF_INET, SOCK_STREAM, 0);

    if (server_fd == -1) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    // --- 2. ๋ฐ”์ธ๋”ฉ / Binding --- //
    struct sockaddr_in address;
    address.sin_family = AF_INET;           // IPv4
    address.sin_addr.s_addr = INADDR_ANY;   // ๋ชจ๋“  ์ธํ„ฐํŽ˜์ด์Šค IP ์‚ฌ์šฉ / Use all interface IPs
    address.sin_port = htons(port_number);  // ํฌํŠธ๋ฅผ ๋„คํŠธ์›Œํฌ ๋ฐ”์ดํŠธ ์ˆœ์„œ๋กœ ๋ณ€ํ™˜ / Convert ports to network byte order

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // --- 3. ๋ฆฌ์Šค๋‹ ์‹œ์ž‘ (setsockopt: listen_socket(socket)) --- //
    if (listen(server_fd, BACKLOG) < 0) {
        perror("listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    std::cout << "Server listening on port " << port_number << "..." << std::endl;

    // --- 4. ๋ฉ”์ธ ๋ฃจํ”„ / Accept loop: ํด๋ผ์ด์–ธํŠธ ์—ฐ๊ฒฐ์„ ๋ฌดํ•œํžˆ ๊ธฐ๋‹ค๋ฆผ / Infinitely waiting for client connections --- //

    // ๋ฌดํ•œ๋ฃจํ”„์—์„œ ์ข…๋ฃŒ์‹ ํ˜ธ๋ฅผ ๋ฐ›์œผ๋ฉด ๋ฃจํ”„๋ฅผ ์ข…๋ฃŒ / Exit the loop when the termination signal is received
    while (running.load()) {

        // ์ข…๋ฃŒ์‹ ํ˜ธ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด 0.1์ดˆ ๋Œ€๊ธฐ / Wait for 0.1 seconds to check the termination signal
        std::this_thread::sleep_for(std::chrono::milliseconds(100)); // ๋ถ€ํ•˜ ๋ฐฉ์ง€๋ฅผ ์œ„ํ•ด ๋Œ€๊ธฐ

        // IPv4๊ตฌ์กฐ์ฒด / Structure for IPv4 address
        struct sockaddr_in client_address;
        socklen_t addrlen = sizeof(client_address);

        // accept() ํ•จ์ˆ˜๊ฐ€ ๋ธ”๋กœํ‚น(Blocking) ์ƒํƒœ์—์„œ ํด๋ผ์ด์–ธํŠธ ์—ฐ๊ฒฐ์„ ๊ธฐ๋‹ค๋ฆผ
        // The accept() function waits for client connections in a blocking state.
        int client_socket = accept(server_fd, (struct sockaddr *)&client_address, &addrlen);
        if (running.load() && client_socket < 0) { //
            perror("accept failed");
            continue; // ์‹คํŒจํ–ˆ์œผ๋ฉด ๋‹ค์Œ ๋ฃจํ”„๋ฅผ ๋Œ๋ฉฐ ์žฌ์‹œ๋„ / Retry in the next loop if it fails
        }
        // ํด๋ผ์ด์–ธํŠธ ์ ‘์† / Client connected
        std::thread client_thread([this, client_socket]() {
            this->handle_client(client_socket); //์™ธ๋ถ€์—์„œ ๋ฉ”์„ธ์ง€ ๋ฐ”๊พธ๊ธฐ
        });

        client_thread.detach();
    }
}

// ์ปค๋งจ๋“œ ์ž…๋ ฅ ๋ฃจํ”„ / Command input loop โ—๏ธ
void Server::run_cmd(){
    std::string command;
    while (true) {
        std::cout << "CMD> "; // ๋ช…๋ น์–ด ํ”„๋กฌํ”„ํŠธ ํ‘œ์‹œ / Show command prompt

        // std::getline์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ณต๋ฐฑ์„ ํฌํ•จํ•œ ์ „์ฒด ๋ฌธ์ž์—ด์„ ํ•œ ๋ฒˆ์— ๋ฐ›์Šต๋‹ˆ๋‹ค.
        // Use std::getline to get the entire string including spaces at once.
        if (!std::getline(std::cin, command)) {
            // EOF (Ctrl+C ๋“ฑ)๋กœ ์ž…๋ ฅ์„ ๋ฐ›์„ ์ˆ˜ ์—†๋Š” ์ƒํ™ฉ์ด ๋ฐœ์ƒํ•˜๋ฉด ์ข…๋ฃŒ
            // Terminate if input cannot be received due to EOF (Ctrl+C, etc.)
            break;
        }

        // ์ž…๋ ฅ๋œ ๋ช…๋ น์–ด๋ฅผ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. / Check the input command
        if (command.empty()) {
            // ์•„๋ฌด๊ฒƒ๋„ ์ž…๋ ฅํ•˜์ง€ ์•Š์•˜์œผ๋ฉด ๊ทธ๋ƒฅ ๋„˜์–ด๊ฐ‘๋‹ˆ๋‹ค./ If you don't enter anything, it will just skip.
            continue;
        } else if (command == "/exit" || command == "exit") {

            std::cout << "[INFO] ์ข…๋ฃŒ ๋ช…๋ น์„ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค ์ข…๋ฃŒ๋ฅผ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.\n";
            std::cout << "[INFO] Received a shutdown command. Starting service shutdown.\n";
            break; // ๋ฃจํ”„ ์ข…๋ฃŒ / Loop End

        } else if (command == "/status") {
            std::cout << "[STATUS] ์„œ๋น„์Šค๋Š” ์ •์ƒ์ ์œผ๋กœ ์ž‘๋™ ์ค‘์ž…๋‹ˆ๋‹ค.\n";
            std::cout << "[STATUS] The service is running normally.\n";
        } else {
            std::cout << "[ERROR] ์•Œ ์ˆ˜ ์—†๋Š” ๋ช…๋ น์–ด์ž…๋‹ˆ๋‹ค. (/exit, /status)\n";
            std::cout << "[ERROR] Unknown command. (/exit, /status)\n";
        }
    }
}

// ๋žŒ๋‹ค์‹์œผ๋กœ ์™ธ๋ถ€์—์„œ ๋‚ด์šฉ ๋ฐ”๊พธ๊ธฐ
// Change content from the outside using a lambda expression
void Server::handle_client(int client_socket) {
    char buffer[1024];
    std::cout << "[Connection] New client connected." << std::endl;

    // 1. ๋ฐ์ดํ„ฐ ์ˆ˜์‹  / receive data
    ssize_t bytes_read = read(client_socket, buffer, sizeof(buffer) - 1);
    if (bytes_read > 0) {
        buffer[bytes_read] = '\0';
        std::string request = buffer;
        std::cout << "[Received] " << request.substr(0, 30) << "..." << std::endl;

        std::string html_content;
        if (logic_handler) {

            // main์—์„œ ๋ณด๋‚ธ ๋žŒ๋‹ค์‹ ์‹คํ–‰,request๋Š” ๋ฒ„ํผ์˜ ๊ฐ’...
            // Execute the lambda expression sent from main, request is the buffer value...
            html_content = logic_handler(request);

        } else {
            html_content = "<h1>No Logic Handler set!</h1>";
        }

        // HTTP ํฌ๋งท ์‘๋‹ต / send HTTP response
        std::string response = "HTTP/1.1 200 OK\r\n"
                               "Content-Type: text/html; charset=utf-8\r\n"
                               "Content-Length: " + std::to_string(html_content.size()) + "\r\n"
                               "\r\n" + html_content;

        write(client_socket, response.c_str(), response.size());
    }

    // 2. ์—ฐ๊ฒฐ ์ข…๋ฃŒ (if๋ฌธ ๋ฐ–์œผ๋กœ ์ด๋™ํ•˜์—ฌ ๋ฌด์กฐ๊ฑด ๋‹ซํžˆ๊ฒŒ ์„ค์ •)
    // 2. Close connection (move outside the if statement and set to close unconditionally)
    close(client_socket);
    std::cout << "[Connection] Client disconnected." << std::endl;
}


bool Server::start() {
    // ์„œ๋ฒ„๊ฐ€ ์‹ค์ œ๋กœ ์ž‘๋™ํ•˜๋Š” ๋ฉ”์ธ ํ•จ์ˆ˜ / Main function that actually runs the server
    try {
        if (!running.load()) {
            running.store(true);
            run_listener();
            return false;
        }

    } catch (const std::exception& e) {
        std::cerr << "[ERROR] Server failed to start: " << e.what() << std::endl;
        return false;
    }
    return true;
}

void Server::stop() {

    if (running.load() && server_fd != -1) { //
        // ํ”Œ๋ž˜๊ทธ๋ฅผ false๋กœ ์„ค์ •ํ•˜์—ฌ ๋ฃจํ”„ ์ข…๋ฃŒ ์‹ ํ˜ธ ์ „์†ก
        // Set flag to false to send loop termination signal
        running.store(false);
        close(server_fd);
        // ์‹ค์ œ๋กœ๋Š” ์—ฌ๊ธฐ์„œ ์†Œ์ผ“์„ ๋‹ซ๊ฑฐ๋‚˜ ๋ฆฌ์†Œ์Šค ํ•ด์ œ๋ฅผ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.
        // In practice, close the socket or release resources here.
        server_fd = -1; // ๋‹ซ์•˜์œผ๋ฏ€๋กœ ์ดˆ๊ธฐํ™” / Initialize to -1 after closing
        std::cout << "[Server] Shutdown initiated." << std::endl;
    }
}

โœ”๏ธ Router.h

#ifndef ROUTER_H
#define ROUTER_H

#include <string>
#include <map>
#include <functional>
#include <utility> // std::pair ์‚ฌ์šฉ์„ ์œ„ํ•ด ์ถ”๊ฐ€ / add std::pair for use

class Router {
    public:
        Router(); // ์ƒ์„ฑ์ž ์„ ์–ธ / constructor declaration
        std::pair<std::string, std::string> router(const std::string& request); // ํ•จ์ˆ˜ ์„ ์–ธ / function declarationโ—๏ธ
    };

#endif // ROUTER_H

Leave a Reply