WebSocketClient.cpp 5.7 KB

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