|
1 | 1 | #include <drogon/drogon.h> |
2 | 2 | #include <chrono> |
| 3 | +#include <functional> |
| 4 | +#include <mutex> |
| 5 | +#include <unordered_map> |
| 6 | +#include <trantor/utils/Logger.h> |
| 7 | +#include <trantor/net/callbacks.h> |
| 8 | +#include <trantor/net/TcpConnection.h> |
3 | 9 |
|
4 | 10 | using namespace drogon; |
5 | 11 | using namespace std::chrono_literals; |
6 | 12 |
|
| 13 | +std::mutex mutex; |
| 14 | +std::unordered_map<trantor::TcpConnectionPtr, std::function<void()>> |
| 15 | + connMapping; |
| 16 | + |
7 | 17 | int main() |
8 | 18 | { |
9 | 19 | app().registerHandler( |
10 | 20 | "/stream", |
11 | | - [](const HttpRequestPtr &, |
| 21 | + [](const HttpRequestPtr &req, |
12 | 22 | std::function<void(const HttpResponsePtr &)> &&callback) { |
| 23 | + const auto &weakConnPtr = req->getConnectionPtr(); |
| 24 | + if (auto connPtr = weakConnPtr.lock()) |
| 25 | + { |
| 26 | + std::lock_guard lk(mutex); |
| 27 | + connMapping.emplace(std::move(connPtr), [] { |
| 28 | + LOG_INFO << "call stop or other options!!!!"; |
| 29 | + }); |
| 30 | + } |
13 | 31 | auto resp = drogon::HttpResponse::newAsyncStreamResponse( |
14 | 32 | [](drogon::ResponseStreamPtr stream) { |
15 | 33 | std::thread([stream = |
@@ -79,5 +97,17 @@ int main() |
79 | 97 |
|
80 | 98 | LOG_INFO << "Server running on 127.0.0.1:8848"; |
81 | 99 | app().enableRequestStream(); // This is for request stream. |
| 100 | + app().setConnectionCallback([](const trantor::TcpConnectionPtr &conn) { |
| 101 | + if (conn->disconnected()) |
| 102 | + { |
| 103 | + std::lock_guard lk(mutex); |
| 104 | + if (auto it = connMapping.find(conn); it != connMapping.end()) |
| 105 | + { |
| 106 | + LOG_INFO << "disconnect"; |
| 107 | + connMapping[conn](); |
| 108 | + connMapping.erase(conn); |
| 109 | + } |
| 110 | + } |
| 111 | + }); |
82 | 112 | app().addListener("127.0.0.1", 8848).run(); |
83 | 113 | } |
0 commit comments