Skip to content

Commit

Permalink
Add validation and status checks for WebSocket server start/stop
Browse files Browse the repository at this point in the history
- Enhanced '/start_websocket' endpoint:
- Added a delay to confirm the WebSocket server starts successfully.
- Added validation with 'pgrep' to check if the WebSocket process is running, improving response accuracy.
- Adjusted '/stop_websocket' endpoint to align error handling and status messages.

These refinements ensure reliable WebSocket management and precise API responses regarding the WebSocket server’s state.
  • Loading branch information
arkadiusz committed Oct 30, 2024
1 parent 64eddad commit b1c97cc
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/api_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -203,28 +203,39 @@ void ApiServer::startWebSocket(const http_request& request) {
std::string command = wsPath + " &";
std::cout << "Starting WebSocket server with command: " << command << std::endl;
std::system(command.c_str());

// Short delay and check whether the process is running
std::this_thread::sleep_for(std::chrono::seconds(1));
if (std::system("pgrep -f wsDll") == 0) {
std::cout << "WebSocket server started successfully." << std::endl;
isWebSocketRunning = true;
}
else {
std::cerr << "Failed to start WebSocket server." << std::endl;
isWebSocketRunning = false;
}
});

isWebSocketRunning = true;
request.reply(status_codes::OK, "WebSocket server started successfully");
}).wait();
}

// Stop the WebSocket server
// Stop the WebSocket server by terminating the thread
void ApiServer::stopWebSocket(const http_request& request) {
if (!isWebSocketRunning.load()) {
request.reply(status_codes::BadRequest, "WebSocket server is not running");
return;
}

// Stoppen des WebSocket-Servers durch Beenden des Threads
if (webSocketThread.joinable()) {
std::cout << "Stopping WebSocket server..." << std::endl;
std::system("pkill -f wsDll");
webSocketThread.join();
isWebSocketRunning = false;
request.reply(status_codes::OK, "WebSocket server stopped successfully");
} else {
}
else {
request.reply(status_codes::InternalError, "Failed to stop WebSocket server");
}
}
Expand Down

0 comments on commit b1c97cc

Please sign in to comment.