WebSocketClient.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. virtual ~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. // NOTE: call before open
  33. void setHttpRequest(const HttpRequestPtr& req) {
  34. http_req_ = req;
  35. }
  36. // NOTE: call when onopen
  37. const HttpResponsePtr& getHttpResponse() {
  38. return http_resp_;
  39. }
  40. private:
  41. enum State {
  42. CONNECTING,
  43. CONNECTED,
  44. WS_UPGRADING,
  45. WS_OPENED,
  46. WS_CLOSED,
  47. } state;
  48. HttpParserPtr http_parser_;
  49. HttpRequestPtr http_req_;
  50. HttpResponsePtr http_resp_;
  51. WebSocketParserPtr ws_parser_;
  52. // ping/pong
  53. int ping_interval;
  54. int ping_cnt;
  55. };
  56. }
  57. #endif // HV_WEBSOCKET_CLIENT_H_