1
0

ssecli.cc 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //
  2. // ssecli.cc
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #include <httplib.h>
  8. #include <csignal>
  9. #include <iostream>
  10. using namespace std;
  11. // Global SSEClient pointer for signal handling
  12. httplib::sse::SSEClient *g_sse = nullptr;
  13. void signal_handler(int) {
  14. if (g_sse) { g_sse->stop(); }
  15. }
  16. int main(void) {
  17. // Configuration
  18. const string host = "http://localhost:1234";
  19. const string path = "/event1";
  20. cout << "SSE Client using httplib::sse::SSEClient\n";
  21. cout << "Connecting to: " << host << path << "\n";
  22. cout << "Press Ctrl+C to exit\n\n";
  23. httplib::Client cli(host);
  24. httplib::sse::SSEClient sse(cli, path);
  25. // Set up signal handler for graceful shutdown
  26. g_sse = &sse;
  27. signal(SIGINT, signal_handler);
  28. // Event handlers
  29. sse.on_open([]() { cout << "[Connected]\n\n"; });
  30. sse.on_message([](const httplib::sse::SSEMessage &msg) {
  31. cout << "Event: " << msg.event << "\n";
  32. cout << "Data: " << msg.data << "\n";
  33. if (!msg.id.empty()) { cout << "ID: " << msg.id << "\n"; }
  34. cout << "\n";
  35. });
  36. sse.on_error([](httplib::Error err) {
  37. cerr << "[Error] " << httplib::to_string(err) << "\n";
  38. });
  39. // Start with auto-reconnect (blocking)
  40. sse.start();
  41. cout << "\n[Disconnected]\n";
  42. return 0;
  43. }