diff --git a/src/Http/WebSocketClient.h b/src/Http/WebSocketClient.h index d22f7c28..2010da0f 100644 --- a/src/Http/WebSocketClient.h +++ b/src/Http/WebSocketClient.h @@ -94,6 +94,20 @@ public: _onRecv = nullptr; sendRequest(http_url,fTimeOutSec); } + + void closeWsClient(){ + if(!_onRecv){ + //未连接 + return; + } + WebSocketHeader header; + header._fin = true; + header._reserved = 0; + header._opcode = CLOSE; + //客户端需要加密 + header._mask_flag = true; + WebSocketSplitter::encode(header, nullptr); + } protected: //HttpClientImp override @@ -328,7 +342,9 @@ public: WebSocketClient(ArgsType &&...args) : ClientTypeImp(std::forward(args)...){ _wsClient.reset(new HttpWsClient(*this)); } - ~WebSocketClient() override {} + ~WebSocketClient() override { + _wsClient->closeWsClient(); + } /** * 重载startConnect方法, diff --git a/tests/test_wsClient.cpp b/tests/test_wsClient.cpp index 54100bdd..26b1970a 100644 --- a/tests/test_wsClient.cpp +++ b/tests/test_wsClient.cpp @@ -59,10 +59,11 @@ int main(int argc, char *argv[]) { Logger::Instance().add(std::make_shared()); Logger::Instance().setWriter(std::make_shared()); - WebSocketClient::Ptr client = std::make_shared >(); - client->startConnect("121.40.165.18",8800); - - sem.wait(); + { + WebSocketClient::Ptr client = std::make_shared >(); + client->startConnect("127.0.0.1", 80); + sem.wait(); + } return 0; } diff --git a/tests/test_wsServer.cpp b/tests/test_wsServer.cpp index e93ea7e7..1a342cef 100644 --- a/tests/test_wsServer.cpp +++ b/tests/test_wsServer.cpp @@ -96,26 +96,28 @@ int main(int argc, char *argv[]) { SSL_Initor::Instance().loadCertificate((exeDir() + "ssl.p12").data()); - TcpServer::Ptr httpSrv(new TcpServer()); - //http服务器,支持websocket - httpSrv->start >(80);//默认80 + { + TcpServer::Ptr httpSrv(new TcpServer()); + //http服务器,支持websocket + httpSrv->start >(80);//默认80 - TcpServer::Ptr httpsSrv(new TcpServer()); - //https服务器,支持websocket - httpsSrv->start >(443);//默认443 + TcpServer::Ptr httpsSrv(new TcpServer()); + //https服务器,支持websocket + httpsSrv->start >(443);//默认443 - TcpServer::Ptr httpSrvOld(new TcpServer()); - //兼容之前的代码(但是不支持根据url选择生成TcpSession类型) - httpSrvOld->start >(8080); + TcpServer::Ptr httpSrvOld(new TcpServer()); + //兼容之前的代码(但是不支持根据url选择生成TcpSession类型) + httpSrvOld->start >(8080); - DebugL << "请打开网页:http://www.websocket-test.com/,进行测试"; - DebugL << "连接 ws://127.0.0.1/xxxx,ws://127.0.0.1/ 测试的效果将不同,支持根据url选择不同的处理逻辑"; + DebugL << "请打开网页:http://www.websocket-test.com/,进行测试"; + DebugL << "连接 ws://127.0.0.1/xxxx,ws://127.0.0.1/ 测试的效果将不同,支持根据url选择不同的处理逻辑"; + //设置退出信号处理函数 + static semaphore sem; + signal(SIGINT, [](int) { sem.post(); });// 设置退出信号 + sem.wait(); + } - //设置退出信号处理函数 - static semaphore sem; - signal(SIGINT, [](int) { sem.post(); });// 设置退出信号 - sem.wait(); return 0; }