http_wsserver.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #pragma once
  2. #include "http_define.h"
  3. #if USE_NET_HTTP_WS == 1
  4. #include <string_view>
  5. #include <functional>
  6. #include "base/define.h"
  7. #include "base/error.h"
  8. class wsserver_lst;
  9. namespace ylib
  10. {
  11. namespace network
  12. {
  13. namespace http
  14. {
  15. /// <summary>
  16. /// WebSocket服务器
  17. /// </summary>
  18. class wsserver:public ylib::error_base {
  19. public:
  20. wsserver();
  21. ~wsserver();
  22. /// <summary>
  23. /// 启动
  24. /// </summary>
  25. /// <param name="port"></param>
  26. /// <param name="ssl"></param>
  27. /// <param name="ssl_key"></param>
  28. /// <param name="ssl_pem"></param>
  29. /// <returns></returns>
  30. bool start(ushort port, bool ssl = false,const std::string& ssl_key = "", const std::string& ssl_pem = "");
  31. /// <summary>
  32. /// 停止
  33. /// </summary>
  34. void stop();
  35. /// <summary>
  36. /// 发送
  37. /// </summary>
  38. bool send(int64 conn, std::string_view value);
  39. /// @brief 断开连接
  40. /// @param conn
  41. void disconn(int64 conn);
  42. void on_accept(std::function<bool(int64)> callback) { m_callback_accept = callback; }
  43. void on_recv(std::function<bool(int64,const char* data, int len)> callback) { m_callback_recv = callback; }
  44. void on_close(std::function<void(int64)> callback) { m_callback_close = callback; }
  45. friend class wsserver_lst;
  46. private:
  47. // 端口
  48. ushort m_port = 0;
  49. // 是否为SSL
  50. bool m_ssl = false;
  51. // SSL-KEY
  52. std::string m_ssl_key;
  53. // SSL-PEM
  54. std::string m_ssl_pem;
  55. // 监听器
  56. wsserver_lst* m_listener = nullptr;
  57. // HPServer
  58. void* m_server = nullptr;
  59. public:
  60. std::function<bool(int64)> m_callback_accept;
  61. std::function<bool(int64,const char* data, int len)> m_callback_recv;
  62. std::function<void(int64)> m_callback_close;
  63. };
  64. }
  65. }
  66. }
  67. #endif