Skip to content

Commit

Permalink
Impl WebSocketClient redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
ithewei committed Nov 14, 2022
1 parent 3a67fe5 commit f0ee909
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions http/client/WebSocketClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
}
}
hlogi("%s", url.c_str());
http_req_.reset(new HttpRequest);
if (!http_req_) {
http_req_.reset(new HttpRequest);
}
// ws => http
http_req_->url = "http" + url.substr(2, -1);
http_req_->ParseUrl();
Expand Down Expand Up @@ -107,7 +109,22 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
size -= nparse;
if (http_parser_->IsComplete()) {
if (http_resp_->status_code != HTTP_STATUS_SWITCHING_PROTOCOLS) {
hloge("server side not support websocket!");
// printf("websocket response:\n%s\n", http_resp_->Dump(true, true).c_str());
if (http_req_->redirect && HTTP_STATUS_IS_REDIRECT(http_resp_->status_code)) {
std::string location = http_resp_->headers["Location"];
if (!location.empty()) {
hlogi("redirect %s => %s", http_req_->url.c_str(), location.c_str());
std::string ws_url = location;
if (hv::startswith(location, "http")) {
ws_url = hv::replace(location, "http", "ws");
}
// NOTE: not triggle onclose when redirecting.
channel->onclose = NULL;
open(ws_url.c_str());
return;
}
}
hloge("server side could not upgrade to websocket: status_code=%d", http_resp_->status_code);
channel->close();
return;
}
Expand Down

0 comments on commit f0ee909

Please sign in to comment.