diff options
author | ipknHama <ipknhama@gmail.com> | 2014-08-07 01:18:33 +0900 |
---|---|---|
committer | ipknHama <ipknhama@gmail.com> | 2014-08-07 01:18:33 +0900 |
commit | 031615ac866cc3c8f1900dd4b4aae2106ad31230 (patch) | |
tree | b8b7206ffbd2043368580ec269c97436929fe452 /examples/example_chat.cpp | |
parent | a0c93f5b84cc11b30bc6320ac26127832ef8bf7a (diff) | |
download | crow-031615ac866cc3c8f1900dd4b4aae2106ad31230.tar.gz crow-031615ac866cc3c8f1900dd4b4aae2106ad31230.zip |
source resturcturing + CMake
Diffstat (limited to 'examples/example_chat.cpp')
-rw-r--r-- | examples/example_chat.cpp | 92 |
1 files changed, 92 insertions, 0 deletions
diff --git a/examples/example_chat.cpp b/examples/example_chat.cpp new file mode 100644 index 0000000..b12926a --- /dev/null +++ b/examples/example_chat.cpp @@ -0,0 +1,92 @@ +#include "crow.h" +#include "json.h" +#include "mustache.h" +#include <string> +#include <vector> +#include <chrono> + +using namespace std; + +vector<string> msgs; +vector<pair<crow::response*, decltype(chrono::steady_clock::now())>> ress; + +void broadcast(const string& msg) +{ + msgs.push_back(msg); + crow::json::wvalue x; + x["msgs"][0] = msgs.back(); + x["last"] = msgs.size(); + string body = crow::json::dump(x); + for(auto p:ress) + { + auto* res = p.first; + CROW_LOG_DEBUG << res << " replied: " << body; + res->end(body); + } + ress.clear(); +} + +int main() +{ + crow::App app; + crow::mustache::set_base("."); + + CROW_ROUTE(app, "/") + ([]{ + crow::mustache::context ctx; + return crow::mustache::load("example_chat.html").render(); + }); + + CROW_ROUTE(app, "/logs") + ([]{ + CROW_LOG_INFO << "logs requested"; + crow::json::wvalue x; + int start = max(0, (int)msgs.size()-100); + for(int i = start; i < (int)msgs.size(); i++) + x["msgs"][i-start] = msgs[i]; + x["last"] = msgs.size(); + CROW_LOG_INFO << "logs completed"; + return x; + }); + + CROW_ROUTE(app, "/logs/<int>") + ([](const crow::request& req, crow::response& res, int after){ + CROW_LOG_INFO << "logs with last " << after; + if (after < (int)msgs.size()) + { + crow::json::wvalue x; + for(int i = after; i < (int)msgs.size(); i ++) + x["msgs"][i-after] = msgs[i]; + x["last"] = msgs.size(); + + res.write(crow::json::dump(x)); + res.end(); + } + else + { + vector<pair<crow::response*, decltype(chrono::steady_clock::now())>> filtered; + for(auto p : ress) + { + if (p.first->is_alive() && chrono::steady_clock::now() - p.second < chrono::seconds(30)) + filtered.push_back(p); + else + p.first->end(); + } + ress.swap(filtered); + ress.push_back({&res, chrono::steady_clock::now()}); + CROW_LOG_DEBUG << &res << " stored " << ress.size(); + } + }); + + CROW_ROUTE(app, "/send") + ([](const crow::request& req) + { + CROW_LOG_INFO << "msg from client: " << req.body; + broadcast(req.body); + return ""; + }); + + app.port(40080) + //.multithreaded() + .run(); +} |