WebSocketClient.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // PATCH: onmessage not given opcode
  19. enum ws_opcode opcode() { return channel ? channel->opcode : WS_OPCODE_CLOSE; }
  20. WebSocketClient(EventLoopPtr loop = NULL);
  21. ~WebSocketClient();
  22. // url = ws://ip:port/path
  23. // url = wss://ip:port/path
  24. int open(const char* url, const http_headers& headers = DefaultHeaders);
  25. int close();
  26. int send(const std::string& msg);
  27. int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY);
  28. // setConnectTimeout / setPingInterval / setReconnect
  29. void setPingInterval(int ms) {
  30. ping_interval = ms;
  31. }
  32. private:
  33. enum State {
  34. CONNECTING,
  35. CONNECTED,
  36. WS_UPGRADING,
  37. WS_OPENED,
  38. WS_CLOSED,
  39. } state;
  40. HttpParserPtr http_parser_;
  41. HttpRequestPtr http_req_;
  42. HttpResponsePtr http_resp_;
  43. WebSocketParserPtr ws_parser_;
  44. // ping/pong
  45. int ping_interval;
  46. int ping_cnt;
  47. };
  48. }
  49. #endif // HV_WEBSOCKET_CLIENT_H_