|
| 1 | + |
| 2 | +#include "WSListener.hpp" |
| 3 | + |
| 4 | +#include "oatpp-websocket/WebSocket.hpp" |
| 5 | +#include "oatpp-websocket/Connector.hpp" |
| 6 | + |
| 7 | +#include "oatpp-mbedtls/client/ConnectionProvider.hpp" |
| 8 | +#include "oatpp-mbedtls/Config.hpp" |
| 9 | + |
| 10 | +#include <thread> |
| 11 | + |
| 12 | +namespace { |
| 13 | + |
| 14 | + bool finished = false; |
| 15 | + |
| 16 | + void socketTask(const std::shared_ptr<oatpp::websocket::WebSocket>& websocket) { |
| 17 | + websocket->listen(); |
| 18 | + OATPP_LOGD("websocket-client", "SOCKET CLOSED!!!"); |
| 19 | + finished = true; |
| 20 | + } |
| 21 | + |
| 22 | +} |
| 23 | + |
| 24 | +void run() { |
| 25 | + |
| 26 | + OATPP_LOGI("websocket-client", "Application Started"); |
| 27 | + |
| 28 | + auto config = oatpp::mbedtls::Config::createDefaultClientConfigShared(); |
| 29 | + |
| 30 | + auto connectionProvider = oatpp::mbedtls::client::ConnectionProvider::createShared(config, "echo.websocket.org", 443); |
| 31 | + |
| 32 | + auto connector = oatpp::websocket::Connector::createShared(connectionProvider); |
| 33 | + |
| 34 | + auto connection = connector->connect("/"); |
| 35 | + |
| 36 | + OATPP_LOGI("websocket-client", "Connected"); |
| 37 | + |
| 38 | + auto socket = oatpp::websocket::WebSocket::createShared(connection, true /* maskOutgoingMessages must be true for clients */); |
| 39 | + |
| 40 | + std::mutex socketWriteMutex; |
| 41 | + |
| 42 | + socket->setListener(std::make_shared<WSListener>(socketWriteMutex)); |
| 43 | + |
| 44 | + std::thread thread(socketTask, socket); |
| 45 | + |
| 46 | + while(!finished) { |
| 47 | + { |
| 48 | + OATPP_LOGD("websocket-client", "sending message..."); |
| 49 | + std::lock_guard<std::mutex> lock(socketWriteMutex); |
| 50 | + socket->sendOneFrameText("hello"); |
| 51 | + } |
| 52 | + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); |
| 53 | + } |
| 54 | + |
| 55 | + thread.join(); |
| 56 | + |
| 57 | +} |
| 58 | + |
| 59 | +int main() { |
| 60 | + oatpp::base::Environment::init(); |
| 61 | + run(); |
| 62 | + oatpp::base::Environment::destroy(); |
| 63 | + return 0; |
| 64 | +} |
0 commit comments