1
0

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