WebSocketClient.cpp 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. onConnection = [this](const WebSocketChannelPtr& channel) {
  54. if (channel->isConnected()) {
  55. state = CONNECTED;
  56. // websocket_handshake
  57. http_req_.reset(new HttpRequest);
  58. http_req_->method = HTTP_GET;
  59. // ws => http
  60. http_req_->url = "http" + url.substr(2, -1);
  61. http_req_->headers["Connection"] = "Upgrade";
  62. http_req_->headers["Upgrade"] = "websocket";
  63. // generate SEC_WEBSOCKET_KEY
  64. unsigned char rand_key[16] = {0};
  65. int *p = (int*)rand_key;
  66. for (int i = 0; i < 4; ++i, ++p) {
  67. *p = rand();
  68. }
  69. char ws_key[32] = {0};
  70. base64_encode(rand_key, 16, ws_key);
  71. http_req_->headers[SEC_WEBSOCKET_KEY] = ws_key;
  72. http_req_->headers[SEC_WEBSOCKET_VERSION] = "13";
  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_.reset(new 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. if (state == WS_UPGRADING) {
  89. int nparse = http_parser_->FeedRecvData((const char*)buf->data(), buf->size());
  90. if (nparse != buf->size()) {
  91. hloge("http parse error!");
  92. channel->close();
  93. return;
  94. }
  95. if (http_parser_->IsComplete()) {
  96. if (http_resp_->status_code != HTTP_STATUS_SWITCHING_PROTOCOLS) {
  97. hloge("server side not support websockt!");
  98. channel->close();
  99. return;
  100. }
  101. std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY);
  102. char ws_accept[32] = {0};
  103. ws_encode_key(ws_key.c_str(), ws_accept);
  104. std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT);
  105. if (strcmp(ws_accept, ws_accept2.c_str()) != 0) {
  106. hloge("Sec-WebSocket-Accept not match!");
  107. channel->close();
  108. return;
  109. }
  110. ws_parser_.reset(new WebSocketParser);
  111. // websocket_onmessage
  112. ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) {
  113. switch (opcode) {
  114. case WS_OPCODE_CLOSE:
  115. channel->close();
  116. break;
  117. case WS_OPCODE_PING:
  118. {
  119. // printf("recv ping\n");
  120. // printf("send pong\n");
  121. channel->write(WS_CLIENT_PONG_FRAME, WS_CLIENT_MIN_FRAME_SIZE);
  122. break;
  123. }
  124. case WS_OPCODE_PONG:
  125. // printf("recv pong\n");
  126. break;
  127. case WS_OPCODE_TEXT:
  128. case WS_OPCODE_BINARY:
  129. if (onmessage) onmessage(msg);
  130. break;
  131. default:
  132. break;
  133. }
  134. };
  135. state = WS_OPENED;
  136. if (onopen) onopen();
  137. }
  138. } else {
  139. int nparse = ws_parser_->FeedRecvData((const char*)buf->data(), buf->size());
  140. if (nparse != buf->size()) {
  141. hloge("websocket parse error!");
  142. channel->close();
  143. return;
  144. }
  145. }
  146. };
  147. state = CONNECTING;
  148. start();
  149. return 0;
  150. }
  151. int WebSocketClient::close() {
  152. if (channel == NULL) return -1;
  153. channel->close();
  154. stop();
  155. state = WS_CLOSED;
  156. return 0;
  157. }
  158. int WebSocketClient::send(const std::string& msg) {
  159. if (channel == NULL) return -1;
  160. return channel->send(msg);
  161. }
  162. }