WebSocketClient.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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(EventLoopPtr loop)
  7. : TcpClientTmpl<WebSocketChannel>(loop)
  8. {
  9. state = WS_CLOSED;
  10. ping_interval = DEFAULT_WS_PING_INTERVAL;
  11. ping_cnt = 0;
  12. }
  13. WebSocketClient::~WebSocketClient() {
  14. stop();
  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. if (!http_req_) {
  35. http_req_ = std::make_shared<HttpRequest>();
  36. }
  37. // ws => http
  38. http_req_->url = "http" + url.substr(2, -1);
  39. http_req_->ParseUrl();
  40. int connfd = createsocket(http_req_->port, http_req_->host.c_str());
  41. if (connfd < 0) {
  42. hloge("createsocket %s:%d return %d!", http_req_->host.c_str(), http_req_->port, connfd);
  43. return connfd;
  44. }
  45. // wss
  46. bool wss = strncmp(url.c_str(), "wss", 3) == 0;
  47. if (wss) {
  48. withTLS();
  49. }
  50. for (auto& header : headers) {
  51. http_req_->headers[header.first] = header.second;
  52. }
  53. onConnection = [this](const WebSocketChannelPtr& channel) {
  54. if (channel->isConnected()) {
  55. state = CONNECTED;
  56. // websocket_handshake
  57. http_req_->headers["Connection"] = "Upgrade";
  58. http_req_->headers["Upgrade"] = "websocket";
  59. if (http_req_->GetHeader(SEC_WEBSOCKET_KEY).empty()) {
  60. // generate SEC_WEBSOCKET_KEY
  61. unsigned char rand_key[16] = {0};
  62. int *p = (int*)rand_key;
  63. for (int i = 0; i < 4; ++i, ++p) {
  64. *p = rand();
  65. }
  66. char ws_key[32] = {0};
  67. hv_base64_encode(rand_key, 16, ws_key);
  68. http_req_->headers[SEC_WEBSOCKET_KEY] = ws_key;
  69. }
  70. if (http_req_->GetHeader(SEC_WEBSOCKET_VERSION).empty()) {
  71. http_req_->headers[SEC_WEBSOCKET_VERSION] = "13";
  72. }
  73. std::string http_msg = http_req_->Dump(true, true);
  74. // printf("%s", http_msg.c_str());
  75. // NOTE: not use WebSocketChannel::send
  76. channel->write(http_msg);
  77. state = WS_UPGRADING;
  78. // prepare HttpParser
  79. http_parser_.reset(HttpParser::New(HTTP_CLIENT, HTTP_V1));
  80. http_resp_ = std::make_shared<HttpResponse>();
  81. http_parser_->InitResponse(http_resp_.get());
  82. } else {
  83. state = WS_CLOSED;
  84. if (onclose) onclose();
  85. }
  86. };
  87. onMessage = [this](const WebSocketChannelPtr& channel, Buffer* buf) {
  88. const char* data = (const char*)buf->data();
  89. size_t size = buf->size();
  90. if (state == WS_UPGRADING) {
  91. int nparse = http_parser_->FeedRecvData(data, size);
  92. if (nparse != size && http_parser_->GetError()) {
  93. hloge("http parse error!");
  94. channel->close();
  95. return;
  96. }
  97. data += nparse;
  98. size -= nparse;
  99. if (http_parser_->IsComplete()) {
  100. if (http_resp_->status_code != HTTP_STATUS_SWITCHING_PROTOCOLS) {
  101. // printf("websocket response:\n%s\n", http_resp_->Dump(true, true).c_str());
  102. if (http_req_->redirect && HTTP_STATUS_IS_REDIRECT(http_resp_->status_code)) {
  103. std::string location = http_resp_->headers["Location"];
  104. if (!location.empty()) {
  105. hlogi("redirect %s => %s", http_req_->url.c_str(), location.c_str());
  106. std::string ws_url = location;
  107. if (hv::startswith(location, "http")) {
  108. ws_url = hv::replace(location, "http", "ws");
  109. }
  110. // NOTE: not triggle onclose when redirecting.
  111. channel->onclose = NULL;
  112. open(ws_url.c_str());
  113. return;
  114. }
  115. }
  116. hloge("server side could not upgrade to websocket: status_code=%d", http_resp_->status_code);
  117. channel->close();
  118. return;
  119. }
  120. std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY);
  121. char ws_accept[32] = {0};
  122. ws_encode_key(ws_key.c_str(), ws_accept);
  123. std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT);
  124. if (strcmp(ws_accept, ws_accept2.c_str()) != 0) {
  125. hloge("Sec-WebSocket-Accept not match!");
  126. channel->close();
  127. return;
  128. }
  129. ws_parser_ = std::make_shared<WebSocketParser>();
  130. // websocket_onmessage
  131. ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) {
  132. channel->opcode = (enum ws_opcode)opcode;
  133. switch (opcode) {
  134. case WS_OPCODE_CLOSE:
  135. channel->send(msg, WS_OPCODE_CLOSE);
  136. channel->close();
  137. break;
  138. case WS_OPCODE_PING:
  139. {
  140. // printf("recv ping\n");
  141. // printf("send pong\n");
  142. channel->send(msg, WS_OPCODE_PONG);
  143. break;
  144. }
  145. case WS_OPCODE_PONG:
  146. // printf("recv pong\n");
  147. ping_cnt = 0;
  148. break;
  149. case WS_OPCODE_TEXT:
  150. case WS_OPCODE_BINARY:
  151. if (onmessage) onmessage(msg);
  152. break;
  153. default:
  154. break;
  155. }
  156. };
  157. state = WS_OPENED;
  158. // ping
  159. if (ping_interval > 0) {
  160. ping_cnt = 0;
  161. channel->setHeartbeat(ping_interval, [this](){
  162. auto& channel = this->channel;
  163. if (channel == NULL) return;
  164. if (ping_cnt++ == 3) {
  165. hloge("websocket no pong!");
  166. channel->close();
  167. return;
  168. }
  169. // printf("send ping\n");
  170. channel->sendPing();
  171. });
  172. }
  173. if (onopen) onopen();
  174. }
  175. }
  176. if (state == WS_OPENED && size != 0) {
  177. int nparse = ws_parser_->FeedRecvData(data, size);
  178. if (nparse != size) {
  179. hloge("websocket parse error!");
  180. channel->close();
  181. return;
  182. }
  183. }
  184. };
  185. state = CONNECTING;
  186. start();
  187. return 0;
  188. }
  189. int WebSocketClient::close() {
  190. closesocket();
  191. state = WS_CLOSED;
  192. return 0;
  193. }
  194. int WebSocketClient::send(const std::string& msg) {
  195. return send(msg.c_str(), msg.size(), WS_OPCODE_TEXT);
  196. }
  197. int WebSocketClient::send(const char* buf, int len, enum ws_opcode opcode) {
  198. if (channel == NULL) return -1;
  199. return channel->send(buf, len, opcode);
  200. }
  201. }