[Webserver]httplib webserver+SSE

👉🏻 SSE는 서버가 클라이언트로 실시간 데이터를 스트리밍(전송)할 수 있도록 해주는 기술입니다.
SSE (Server-Sent Events) is a technology that allows the server to stream real-time data to the client.

👉🏻 SSE 서버 및 클라이언트 / SSE Server and Client

✔️ 코드 / Code

— sse_server.cpp

#include "httplib.h"
#include <chrono>
#include <string>
#include <thread>

int main() {
    httplib::Server svr;

    svr.Get("/", [](const httplib::Request&, httplib::Response& res) {
        res.set_content(R"(
<!doctype html><html><body>
<h1>SSE Test</h1>
<pre id="log"></pre>
<script>
const log = document.getElementById('log');
const es = new EventSource('/events'); // same-origin
es.onopen = () => log.textContent += "[connected]\n";
es.onmessage = (e) => log.textContent += e.data + "\n";
es.onerror = () => log.textContent += "[reconnecting]\n";
</script>
</body></html>
)", "text/html; charset=utf-8");
    });

    svr.Get("/events", [](const httplib::Request&, httplib::Response& res) {
        res.set_header("Cache-Control", "no-cache");
        res.set_header("Connection", "keep-alive");
        res.set_chunked_content_provider("text/event-stream; charset=utf-8",
            [n = 0](size_t, httplib::DataSink& sink) mutable {
                std::string msg = "data: tick " + std::to_string(n++) + "\n\n";
                sink.write(msg.c_str(), msg.size());
                std::this_thread::sleep_for(std::chrono::seconds(1));
                return true; // 계속 연결 유지
            });
    });

    svr.set_keep_alive_max_count(1000);
    svr.set_keep_alive_timeout(60);

    std::cout << "SSE server listening on http://0.0.0.0:5080\n";
    svr.listen("0.0.0.0", 5080);
    return 0;
}

— sse_client.cpp

#include "httplib.h"

int main() {
    httplib::Client cli("http://localhost:5080");
    httplib::sse::SSEClient sse(cli, "/events");

    sse.on_message([](const httplib::sse::SSEMessage &msg) {
        std::cout << "Event: " << msg.event << std::endl;
        std::cout << "Data: " << msg.data << std::endl;
    });

    sse.start();  // Blocking, with auto-reconnect
    return 0;
}

— sse server

g++ sse_server.cpp -o sse_server -std=c++17 -pthread

— sse client

g++ sse_client.cpp -o sse_client -std=c++17 -pthread

✔️실행 / Run

— 서버실행 / Run Server

./sse_server
sse server

— 클라이언트실행 / Run Client

./sse_client

— 브라우저실행 / Access Browser

http://localost:5080

Leave a Reply