1
0

WebSocketClient.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. const char* data = (const char*)buf->data();
  79. size_t size = buf->size();
  80. if (state == WS_UPGRADING) {
  81. int nparse = http_parser_->FeedRecvData(data, size);
  82. if (nparse != size && http_parser_->GetError()) {
  83. hloge("http parse error!");
  84. channel->close();
  85. return;
  86. }
  87. data += nparse;
  88. size -= nparse;
  89. if (http_parser_->IsComplete()) {
  90. if (http_resp_->status_code != HTTP_STATUS_SWITCHING_PROTOCOLS) {
  91. hloge("server side not support websocket!");
  92. channel->close();
  93. return;
  94. }
  95. std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY);
  96. char ws_accept[32] = {0};
  97. ws_encode_key(ws_key.c_str(), ws_accept);
  98. std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT);
  99. if (strcmp(ws_accept, ws_accept2.c_str()) != 0) {
  100. hloge("Sec-WebSocket-Accept not match!");
  101. channel->close();
  102. return;
  103. }
  104. ws_parser_.reset(new WebSocketParser);
  105. // websocket_onmessage
  106. ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) {
  107. switch (opcode) {
  108. case WS_OPCODE_CLOSE:
  109. channel->close();
  110. break;
  111. case WS_OPCODE_PING:
  112. {
  113. // printf("recv ping\n");
  114. // printf("send pong\n");
  115. channel->write(WS_CLIENT_PONG_FRAME, WS_CLIENT_MIN_FRAME_SIZE);
  116. break;
  117. }
  118. case WS_OPCODE_PONG:
  119. // printf("recv pong\n");
  120. ping_cnt = 0;
  121. break;
  122. case WS_OPCODE_TEXT:
  123. case WS_OPCODE_BINARY:
  124. if (onmessage) onmessage(msg);
  125. break;
  126. default:
  127. break;
  128. }
  129. };
  130. state = WS_OPENED;
  131. // ping
  132. if (ping_interval > 0) {
  133. ping_cnt = 0;
  134. channel->setHeartbeat(ping_interval, [this](){
  135. auto& channel = this->channel;
  136. if (channel == NULL) return;
  137. if (ping_cnt++ == 3) {
  138. hloge("websocket no pong!");
  139. channel->close();
  140. return;
  141. }
  142. // printf("send ping\n");
  143. channel->write(WS_CLIENT_PING_FRAME, WS_CLIENT_MIN_FRAME_SIZE);
  144. });
  145. }
  146. if (onopen) onopen();
  147. }
  148. }
  149. if (state == WS_OPENED && size != 0) {
  150. int nparse = ws_parser_->FeedRecvData(data, size);
  151. if (nparse != size) {
  152. hloge("websocket parse error!");
  153. channel->close();
  154. return;
  155. }
  156. }
  157. };
  158. state = CONNECTING;
  159. start();
  160. return 0;
  161. }
  162. int WebSocketClient::close() {
  163. if (channel == NULL) return -1;
  164. channel->close();
  165. stop();
  166. state = WS_CLOSED;
  167. return 0;
  168. }
  169. int WebSocketClient::send(const std::string& msg) {
  170. return send(msg.c_str(), msg.size(), WS_OPCODE_TEXT);
  171. }
  172. int WebSocketClient::send(const char* buf, int len, enum ws_opcode opcode) {
  173. if (channel == NULL) return -1;
  174. return channel->send(buf, len, opcode);
  175. }
  176. }