Skip to content

Commit

Permalink
add sse
Browse files Browse the repository at this point in the history
  • Loading branch information
mattn committed Jan 28, 2024
1 parent 43673eb commit 15d2217
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 4 deletions.
18 changes: 17 additions & 1 deletion clask/core.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,22 @@ class response_writer {
virtual void end();
};

class server_sent_event_writer {
private:
response_writer w;
public:
server_sent_event_writer(response_writer& w) : w(w) {
w.set_header("Transfer-Encoding", "chunked");
};
void write(const std::string& event, const std::string& data) {
w.write("event: " + event + "\r\n");
w.write("data: " + data + "\r\n");
w.write("\r\n");
}
void end() {
w.end();
}
};
class chunked_writer {
private:
response_writer w;
Expand All @@ -386,10 +402,10 @@ class chunked_writer {
}
void end() {
w.write("0\r\n\r\n");
w.end();
}
};


inline std::unordered_map<std::string, std::string> params(const std::string& s) {
std::unordered_map<std::string, std::string> ret;
std::istringstream iss(s);
Expand Down
7 changes: 4 additions & 3 deletions example/stream/main.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
int main() {
auto s = clask::server();

s.GET("/", [&](clask::response_writer& w, clask::request& r) {
s.static_dir("/", "./public");
s.GET("/api", [&](clask::response_writer& w, clask::request& r) {
w.code = 200;
w.set_header("content-type", "text/event-stream; charset=utf-8");
w.write_headers();

clask::chunked_writer ww(w);
clask::server_sent_event_writer ww(w);
for (int n = 0; n < 100; n++) {
ww.write("💩");
ww.write("unko", R"("💩")");
usleep(100000);
}
ww.end();
Expand Down
22 changes: 22 additions & 0 deletions example/stream/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
<script>
window.addEventListener('DOMContentLoaded', function() {
const es = new EventSource("/api");
es.addEventListener("unko", (ev) => {
const unko = JSON.parse(ev.data);
const dom = document.querySelector('#container');
const e = document.createElement('span');
e.textContent = unko;
dom.appendChild(e);
});
}, false);
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>

0 comments on commit 15d2217

Please sign in to comment.