WebSocketClient.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #ifndef HV_WEBSOCKET_CLIENT_H_
  2. #define HV_WEBSOCKET_CLIENT_H_
  3. /*
  4. * @demo examples/websocket_client_test.cpp
  5. */
  6. #include "hexport.h"
  7. #include "TcpClient.h"
  8. #include "WebSocketChannel.h"
  9. #include "HttpParser.h"
  10. #include "WebSocketParser.h"
  11. namespace hv {
  12. class HV_EXPORT WebSocketClient : public TcpClientTmpl<WebSocketChannel> {
  13. public:
  14. std::string url;
  15. std::function<void()> onopen;
  16. std::function<void()> onclose;
  17. std::function<void(const std::string& msg)> onmessage;
  18. WebSocketClient();
  19. ~WebSocketClient();
  20. // url = ws://ip:port/path
  21. // url = wss://ip:port/path
  22. int open(const char* url, const http_headers& headers = DefaultHeaders);
  23. int close();
  24. int send(const std::string& msg);
  25. int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY);
  26. // setConnectTimeout / setPingInterval / setReconnect
  27. void setPingInterval(int ms) {
  28. ping_interval = ms;
  29. }
  30. private:
  31. enum State {
  32. CONNECTING,
  33. CONNECTED,
  34. WS_UPGRADING,
  35. WS_OPENED,
  36. WS_CLOSED,
  37. } state;
  38. HttpParserPtr http_parser_;
  39. HttpRequestPtr http_req_;
  40. HttpResponsePtr http_resp_;
  41. WebSocketParserPtr ws_parser_;
  42. // ping/pong
  43. int ping_interval;
  44. int ping_cnt;
  45. };
  46. }
  47. #endif // HV_WEBSOCKET_CLIENT_H_