|
| 1 | +/* |
| 2 | + This file is part of libhttpserver |
| 3 | + Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino |
| 4 | +
|
| 5 | + This library is free software; you can redistribute it and/or |
| 6 | + modify it under the terms of the GNU Lesser General Public |
| 7 | + License as published by the Free Software Foundation; either |
| 8 | + version 2.1 of the License, or (at your option) any later version. |
| 9 | +
|
| 10 | + This library is distributed in the hope that it will be useful, |
| 11 | + but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 | + Lesser General Public License for more details. |
| 14 | +
|
| 15 | + You should have received a copy of the GNU Lesser General Public |
| 16 | + License along with this library; if not, write to the Free Software |
| 17 | + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 |
| 18 | + USA |
| 19 | +*/ |
| 20 | + |
| 21 | +#include <atomic> |
| 22 | +#include <httpserver.hpp> |
| 23 | + |
| 24 | +using namespace httpserver; |
| 25 | + |
| 26 | +std::atomic<int> counter; |
| 27 | + |
| 28 | +ssize_t test_callback (std::shared_ptr<std::atomic<int> > closure_data, char* buf, size_t max) { |
| 29 | + int reqid; |
| 30 | + if (closure_data == nullptr) { |
| 31 | + reqid = -1; |
| 32 | + } else { |
| 33 | + reqid = *closure_data; |
| 34 | + } |
| 35 | + |
| 36 | + // only first 5 connections can be established |
| 37 | + if (reqid >= 5) { |
| 38 | + return -1; |
| 39 | + } else { |
| 40 | + // respond corresponding request IDs to the clients |
| 41 | + std::string str = ""; |
| 42 | + str += std::to_string(reqid) + " "; |
| 43 | + memset(buf, 0, max); |
| 44 | + std::copy(str.begin(), str.end(), buf); |
| 45 | + |
| 46 | + // keep sending reqid |
| 47 | + sleep(1); |
| 48 | + |
| 49 | + return (ssize_t)max; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +class deferred_resource : public http_resource { |
| 54 | + public: |
| 55 | + const std::shared_ptr<http_response> render_GET(const http_request& req) { |
| 56 | + std::shared_ptr<std::atomic<int> > closure_data(new std::atomic<int>(counter++)); |
| 57 | + return std::shared_ptr<deferred_response<std::atomic<int> > >(new deferred_response<std::atomic<int> >(test_callback, closure_data, "cycle callback response")); |
| 58 | + } |
| 59 | +}; |
| 60 | + |
| 61 | +int main(int argc, char** argv) { |
| 62 | + webserver ws = create_webserver(8080); |
| 63 | + |
| 64 | + deferred_resource hwr; |
| 65 | + ws.register_resource("/hello", &hwr); |
| 66 | + ws.start(true); |
| 67 | + |
| 68 | + return 0; |
| 69 | +} |
| 70 | + |
0 commit comments