Add the Host and Sec-WebSocket-Version headers when connecting to a websocket server (#615)

This commit is contained in:
An Tao 2020-10-25 08:36:40 +08:00 committed by GitHub
parent ed2818ed89
commit de37a0ae29
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 2 deletions

View File

@ -11,13 +11,20 @@ int main(int argc, char *argv[])
{ {
auto wsPtr = WebSocketClient::newWebSocketClient("127.0.0.1", 8848); auto wsPtr = WebSocketClient::newWebSocketClient("127.0.0.1", 8848);
auto req = HttpRequest::newHttpRequest(); auto req = HttpRequest::newHttpRequest();
req->setPath("/chat");
bool continually = true; bool continually = true;
if (argc > 1) if (argc > 1)
{ {
if (std::string(argv[1]) == "-t") if (std::string(argv[1]) == "-t")
continually = false; 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, wsPtr->setMessageHandler([continually](const std::string &message,
const WebSocketClientPtr &wsPtr, const WebSocketClientPtr &wsPtr,
const WebSocketMessageType &type) { const WebSocketMessageType &type) {
@ -60,5 +67,6 @@ int main(int argc, char *argv[])
exit(1); exit(1);
} }
}); });
app().setLogLevel(trantor::Logger::kTrace);
app().run(); app().run();
} }

View File

@ -95,6 +95,15 @@ void WebSocketClientImpl::connectToServerInLoop()
loop_->assertInLoopThread(); loop_->assertInLoopThread();
upgradeRequest_->addHeader("Connection", "Upgrade"); upgradeRequest_->addHeader("Connection", "Upgrade");
upgradeRequest_->addHeader("Upgrade", "websocket"); 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); auto randStr = utils::genRandomString(16);
wsKey_ = utils::base64Encode((const unsigned char *)randStr.data(), wsKey_ = utils::base64Encode((const unsigned char *)randStr.data(),
(unsigned int)randStr.length()); (unsigned int)randStr.length());

@ -1 +1 @@
Subproject commit 1e5d24ef09f7ca60d888fd9c81bfc85323b1e6da Subproject commit 88c5b846f300858e592217029615c72e89f71265