1
0

WebSocketClient.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #include "WebSocketClient.h"
  2. #include "base64.h"
  3. #include "hlog.h"
  4. #define DEFAULT_WS_PING_INTERVAL 3000 // ms
  5. namespace hv {
  6. WebSocketClient::WebSocketClient()
  7. : TcpClientTmpl<WebSocketChannel>()
  8. {
  9. state = WS_CLOSED;
  10. ping_interval = DEFAULT_WS_PING_INTERVAL;
  11. ping_cnt = 0;
  12. }
  13. WebSocketClient::~WebSocketClient() {
  14. close();
  15. }
  16. /*
  17. * ParseUrl => createsocket => start =>
  18. * TCP::onConnection => websocket_handshake => WS::onopen =>
  19. * TCP::onMessage => WebSocketParser => WS::onmessage =>
  20. * TCP::onConnection => WS::onclose
  21. */
  22. int WebSocketClient::open(const char* _url) {
  23. close();
  24. // ParseUrl
  25. if (_url) {
  26. if (strncmp(_url, "ws", 2) != 0) {
  27. url = "ws://";
  28. url += _url;
  29. } else {
  30. url = _url;
  31. }
  32. }
  33. hlogi("%s", url.c_str());
  34. http_req_.reset(new HttpRequest);
  35. // ws => http
  36. http_req_->url = "http" + url.substr(2, -1);
  37. http_req_->ParseUrl();
  38. int connfd = createsocket(http_req_->port, http_req_->host.c_str());
  39. if (connfd < 0) {
  40. return connfd;
  41. }
  42. // wss
  43. bool wss = strncmp(url.c_str(), "wss", 3) == 0;
  44. if (wss) {
  45. withTLS();
  46. }
  47. onConnection = [this](const WebSocketChannelPtr& channel) {
  48. if (channel->isConnected()) {
  49. state = CONNECTED;
  50. // websocket_handshake
  51. http_req_->headers["Connection"] = "Upgrade";
  52. http_req_->headers["Upgrade"] = "websocket";
  53. // generate SEC_WEBSOCKET_KEY
  54. unsigned char rand_key[16] = {0};
  55. int *p = (int*)rand_key;
  56. for (int i = 0; i < 4; ++i, ++p) {
  57. *p = rand();
  58. }
  59. char ws_key[32] = {0};
  60. hv_base64_encode(rand_key, 16, ws_key);
  61. http_req_->headers[SEC_WEBSOCKET_KEY] = ws_key;
  62. http_req_->headers[SEC_WEBSOCKET_VERSION] = "13";
  63. std::string http_msg = http_req_->Dump(true, true);
  64. // printf("%s", http_msg.c_str());
  65. // NOTE: not use WebSocketChannel::send
  66. channel->write(http_msg);
  67. state = WS_UPGRADING;
  68. // prepare HttpParser
  69. http_parser_.reset(HttpParser::New(HTTP_CLIENT, HTTP_V1));
  70. http_resp_.reset(new HttpResponse);
  71. http_parser_->InitResponse(http_resp_.get());
  72. } else {
  73. state = WS_CLOSED;
  74. if (onclose) onclose();
  75. }
  76. };
  77. onMessage = [this](const WebSocketChannelPtr& channel, Buffer* buf) {
  78. if (state == WS_UPGRADING) {
  79. int nparse = http_parser_->FeedRecvData((const char*)buf->data(), buf->size());
  80. if (nparse != buf->size()) {
  81. hloge("http parse error!");
  82. channel->close();
  83. return;
  84. }
  85. if (http_parser_->IsComplete()) {
  86. if (http_resp_->status_code != HTTP_STATUS_SWITCHING_PROTOCOLS) {
  87. hloge("server side not support websocket!");
  88. channel->close();
  89. return;
  90. }
  91. std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY);
  92. char ws_accept[32] = {0};
  93. ws_encode_key(ws_key.c_str(), ws_accept);
  94. std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT);
  95. if (strcmp(ws_accept, ws_accept2.c_str()) != 0) {
  96. hloge("Sec-WebSocket-Accept not match!");
  97. channel->close();
  98. return;
  99. }
  100. ws_parser_.reset(new WebSocketParser);
  101. // websocket_onmessage
  102. ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) {
  103. switch (opcode) {
  104. case WS_OPCODE_CLOSE:
  105. channel->close();
  106. break;
  107. case WS_OPCODE_PING:
  108. {
  109. // printf("recv ping\n");
  110. // printf("send pong\n");
  111. channel->write(WS_CLIENT_PONG_FRAME, WS_CLIENT_MIN_FRAME_SIZE);
  112. break;
  113. }
  114. case WS_OPCODE_PONG:
  115. // printf("recv pong\n");
  116. ping_cnt = 0;
  117. break;
  118. case WS_OPCODE_TEXT:
  119. case WS_OPCODE_BINARY:
  120. if (onmessage) onmessage(msg);
  121. break;
  122. default:
  123. break;
  124. }
  125. };
  126. state = WS_OPENED;
  127. // ping
  128. if (ping_interval > 0) {
  129. ping_cnt = 0;
  130. channel->setHeartbeat(ping_interval, [this](){
  131. auto& channel = this->channel;
  132. if (channel == NULL) return;
  133. if (ping_cnt++ == 3) {
  134. hloge("websocket no pong!");
  135. channel->close();
  136. return;
  137. }
  138. // printf("send ping\n");
  139. channel->write(WS_CLIENT_PING_FRAME, WS_CLIENT_MIN_FRAME_SIZE);
  140. });
  141. }
  142. if (onopen) onopen();
  143. }
  144. } else {
  145. int nparse = ws_parser_->FeedRecvData((const char*)buf->data(), buf->size());
  146. if (nparse != buf->size()) {
  147. hloge("websocket parse error!");
  148. channel->close();
  149. return;
  150. }
  151. }
  152. };
  153. state = CONNECTING;
  154. start();
  155. return 0;
  156. }
  157. int WebSocketClient::close() {
  158. if (channel == NULL) return -1;
  159. channel->close();
  160. stop();
  161. state = WS_CLOSED;
  162. return 0;
  163. }
  164. int WebSocketClient::send(const std::string& msg) {
  165. return send(msg.c_str(), msg.size(), WS_OPCODE_TEXT);
  166. }
  167. int WebSocketClient::send(const char* buf, int len, enum ws_opcode opcode) {
  168. if (channel == NULL) return -1;
  169. return channel->send(buf, len, opcode);
  170. }
  171. }