WebSocketClient.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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, const http_headers& headers) {
  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. for (auto& header : headers) {
  48. http_req_->headers[header.first] = header.second;
  49. }
  50. onConnection = [this](const WebSocketChannelPtr& channel) {
  51. if (channel->isConnected()) {
  52. state = CONNECTED;
  53. // websocket_handshake
  54. http_req_->headers["Connection"] = "Upgrade";
  55. http_req_->headers["Upgrade"] = "websocket";
  56. if (http_req_->GetHeader(SEC_WEBSOCKET_KEY).empty()) {
  57. // generate SEC_WEBSOCKET_KEY
  58. unsigned char rand_key[16] = {0};
  59. int *p = (int*)rand_key;
  60. for (int i = 0; i < 4; ++i, ++p) {
  61. *p = rand();
  62. }
  63. char ws_key[32] = {0};
  64. hv_base64_encode(rand_key, 16, ws_key);
  65. http_req_->headers[SEC_WEBSOCKET_KEY] = ws_key;
  66. }
  67. if (http_req_->GetHeader(SEC_WEBSOCKET_VERSION).empty()) {
  68. http_req_->headers[SEC_WEBSOCKET_VERSION] = "13";
  69. }
  70. std::string http_msg = http_req_->Dump(true, true);
  71. // printf("%s", http_msg.c_str());
  72. // NOTE: not use WebSocketChannel::send
  73. channel->write(http_msg);
  74. state = WS_UPGRADING;
  75. // prepare HttpParser
  76. http_parser_.reset(HttpParser::New(HTTP_CLIENT, HTTP_V1));
  77. http_resp_.reset(new HttpResponse);
  78. http_parser_->InitResponse(http_resp_.get());
  79. } else {
  80. state = WS_CLOSED;
  81. if (onclose) onclose();
  82. }
  83. };
  84. onMessage = [this](const WebSocketChannelPtr& channel, Buffer* buf) {
  85. const char* data = (const char*)buf->data();
  86. size_t size = buf->size();
  87. if (state == WS_UPGRADING) {
  88. int nparse = http_parser_->FeedRecvData(data, size);
  89. if (nparse != size && http_parser_->GetError()) {
  90. hloge("http parse error!");
  91. channel->close();
  92. return;
  93. }
  94. data += nparse;
  95. size -= nparse;
  96. if (http_parser_->IsComplete()) {
  97. if (http_resp_->status_code != HTTP_STATUS_SWITCHING_PROTOCOLS) {
  98. hloge("server side not support websocket!");
  99. channel->close();
  100. return;
  101. }
  102. std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY);
  103. char ws_accept[32] = {0};
  104. ws_encode_key(ws_key.c_str(), ws_accept);
  105. std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT);
  106. if (strcmp(ws_accept, ws_accept2.c_str()) != 0) {
  107. hloge("Sec-WebSocket-Accept not match!");
  108. channel->close();
  109. return;
  110. }
  111. ws_parser_.reset(new WebSocketParser);
  112. // websocket_onmessage
  113. ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) {
  114. switch (opcode) {
  115. case WS_OPCODE_CLOSE:
  116. channel->close();
  117. break;
  118. case WS_OPCODE_PING:
  119. {
  120. // printf("recv ping\n");
  121. // printf("send pong\n");
  122. channel->sendPong();
  123. break;
  124. }
  125. case WS_OPCODE_PONG:
  126. // printf("recv pong\n");
  127. ping_cnt = 0;
  128. break;
  129. case WS_OPCODE_TEXT:
  130. case WS_OPCODE_BINARY:
  131. if (onmessage) onmessage(msg);
  132. break;
  133. default:
  134. break;
  135. }
  136. };
  137. state = WS_OPENED;
  138. // ping
  139. if (ping_interval > 0) {
  140. ping_cnt = 0;
  141. channel->setHeartbeat(ping_interval, [this](){
  142. auto& channel = this->channel;
  143. if (channel == NULL) return;
  144. if (ping_cnt++ == 3) {
  145. hloge("websocket no pong!");
  146. channel->close();
  147. return;
  148. }
  149. // printf("send ping\n");
  150. channel->sendPing();
  151. });
  152. }
  153. if (onopen) onopen();
  154. }
  155. }
  156. if (state == WS_OPENED && size != 0) {
  157. int nparse = ws_parser_->FeedRecvData(data, size);
  158. if (nparse != size) {
  159. hloge("websocket parse error!");
  160. channel->close();
  161. return;
  162. }
  163. }
  164. };
  165. state = CONNECTING;
  166. start();
  167. return 0;
  168. }
  169. int WebSocketClient::close() {
  170. if (channel == NULL) return -1;
  171. channel->close();
  172. stop();
  173. state = WS_CLOSED;
  174. return 0;
  175. }
  176. int WebSocketClient::send(const std::string& msg) {
  177. return send(msg.c_str(), msg.size(), WS_OPCODE_TEXT);
  178. }
  179. int WebSocketClient::send(const char* buf, int len, enum ws_opcode opcode) {
  180. if (channel == NULL) return -1;
  181. return channel->send(buf, len, opcode);
  182. }
  183. }