From de37a0ae291b0aade1c03603286b51cdfd2b4bce Mon Sep 17 00:00:00 2001 From: An Tao Date: Sun, 25 Oct 2020 08:36:40 +0800 Subject: [PATCH] Add the Host and Sec-WebSocket-Version headers when connecting to a websocket server (#615) --- examples/simple_example_test/WebSocketTest.cc | 10 +++++++++- lib/src/WebSocketClientImpl.cc | 9 +++++++++ trantor | 2 +- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/examples/simple_example_test/WebSocketTest.cc b/examples/simple_example_test/WebSocketTest.cc index b4fbdebe..c9bc2ad9 100644 --- a/examples/simple_example_test/WebSocketTest.cc +++ b/examples/simple_example_test/WebSocketTest.cc @@ -11,13 +11,20 @@ int main(int argc, char *argv[]) { auto wsPtr = WebSocketClient::newWebSocketClient("127.0.0.1", 8848); auto req = HttpRequest::newHttpRequest(); + req->setPath("/chat"); bool continually = true; if (argc > 1) { if (std::string(argv[1]) == "-t") continually = false; + else if (std::string(argv[1]) == "-p") + { + // Connect to a public web socket server. + wsPtr = + WebSocketClient::newWebSocketClient("wss://echo.websocket.org"); + req->setPath("/"); + } } - req->setPath("/chat"); wsPtr->setMessageHandler([continually](const std::string &message, const WebSocketClientPtr &wsPtr, const WebSocketMessageType &type) { @@ -60,5 +67,6 @@ int main(int argc, char *argv[]) exit(1); } }); + app().setLogLevel(trantor::Logger::kTrace); app().run(); } \ No newline at end of file diff --git a/lib/src/WebSocketClientImpl.cc b/lib/src/WebSocketClientImpl.cc index 528a8c17..df0ff683 100644 --- a/lib/src/WebSocketClientImpl.cc +++ b/lib/src/WebSocketClientImpl.cc @@ -95,6 +95,15 @@ void WebSocketClientImpl::connectToServerInLoop() loop_->assertInLoopThread(); upgradeRequest_->addHeader("Connection", "Upgrade"); upgradeRequest_->addHeader("Upgrade", "websocket"); + bool usePort = ((serverAddr_.toPort() != 80 && !useSSL_) || + (serverAddr_.toPort() != 443 && useSSL_)); + upgradeRequest_->addHeader( + "Host", + domain_.empty() + ? (usePort ? serverAddr_.toIpPort() : serverAddr_.toIp()) + : (usePort ? domain_ + ":" + std::to_string(serverAddr_.toPort()) + : domain_)); + upgradeRequest_->addHeader("Sec-WebSocket-Version", "13"); auto randStr = utils::genRandomString(16); wsKey_ = utils::base64Encode((const unsigned char *)randStr.data(), (unsigned int)randStr.length()); diff --git a/trantor b/trantor index 1e5d24ef..88c5b846 160000 --- a/trantor +++ b/trantor @@ -1 +1 @@ -Subproject commit 1e5d24ef09f7ca60d888fd9c81bfc85323b1e6da +Subproject commit 88c5b846f300858e592217029615c72e89f71265