| 268 | } |
| 269 | |
| 270 | bool start(int port) { |
| 271 | try { |
| 272 | _server.WebSocket(".*", [this](const httplib::Request& req, httplib::ws::WebSocket& ws) { |
| 273 | auto resource = req.target.empty() ? req.path : req.target; |
| 274 | if (_owner && _owner->_authRequired && !_owner->isWebSocketAuthorized(resource)) { |
| 275 | ws.close(httplib::ws::CloseStatus::PolicyViolation, "unauthorized"s); |
| 276 | return; |
| 277 | } |
| 278 | auto connection = std::make_shared<Connection>(&ws); |
| 279 | { |
| 280 | std::lock_guard<std::mutex> guard(_connectionLock); |
| 281 | _connections.insert(connection); |
| 282 | } |
| 283 | SharedApplication.invokeInLogic([]() { |
| 284 | Event::send("AppWS"sv, makeAppWSMessage("Open"_slice)); |
| 285 | }); |
| 286 | std::string msg; |
| 287 | httplib::ws::ReadResult ret; |
| 288 | while ((ret = ws.read(msg))) { |
| 289 | if (ret == httplib::ws::Binary) { |
| 290 | auto message = std::make_shared<std::string>(std::move(msg)); |
| 291 | SharedApplication.invokeInLogic([message = std::move(message)]() { |
| 292 | Event::send("AppWS"sv, makeAppWSMessage("Receive"_slice, std::move(*message))); |
| 293 | }); |
| 294 | } |
| 295 | } |
| 296 | { |
| 297 | std::lock_guard<std::mutex> guard(connection->lock); |
| 298 | connection->webSocket = nullptr; |
| 299 | } |
| 300 | { |
| 301 | std::lock_guard<std::mutex> guard(_connectionLock); |
| 302 | _connections.erase(connection); |
| 303 | } |
| 304 | SharedApplication.invokeInLogic([]() { |
| 305 | Event::send("AppWS"sv, makeAppWSMessage("Close"_slice)); |
| 306 | }); |
| 307 | }); |
| 308 | if (!_server.bind_to_port("0.0.0.0", port)) { |
| 309 | Error("failed to bind websocket server port {}!", port); |
| 310 | return false; |
| 311 | } |
| 312 | { |
| 313 | std::lock_guard<std::mutex> guard(_shutdownLock); |
| 314 | _stopped = false; |
| 315 | } |
| 316 | _thread->run([this]() { |
| 317 | if (!_server.listen_after_bind()) { |
| 318 | Error("websocket server failed to start"); |
| 319 | } |
| 320 | { |
| 321 | std::lock_guard<std::mutex> guard(_shutdownLock); |
| 322 | _stopped = true; |
| 323 | } |
| 324 | _waitForShutdown.notify_all(); |
| 325 | }); |
| 326 | LogHandler += std::make_pair(this, &WebSocketServer::sendLog); |
| 327 | return true; |
nothing calls this directly
no test coverage detected