#include "../include/useriomanager.hpp" #include "../include/commands.hpp" #include #include #include #include using boost::asio::buffer; void UserIoManager::run() { std::cout << "UserIoManager::run() says hello!" << std::endl; bool keep_reading = true; COMMANDID cmd; char *line = NULL; while(keep_reading){ free(line); // read an input line line = readline ("ccats> "); // if no input, do not add to history, and go to reading next line if (strlen(line) == 0) { continue; } // add the line to history add_history(line); cmd = getCmdIdFromString(line); switch(cmd) { case CMD_STATUS: { boost::asio::streambuf recvbuf; Json::Value root, checkok; const char *recvjson; std::string jsonerror; Json::CharReaderBuilder rbuilder; const std::unique_ptr reader(rbuilder.newCharReader()); Json::StreamWriterBuilder wbuilder; // ask for status root["command"] = "status"; boost::asio::write(*tcpsock, buffer(Json::writeString(wbuilder, root)), errcode); if(errcode) { std::cerr << "couldnt send status query to server " << ipstring << std::endl << errcode.message() << std::endl; keep_reading = false; continue; } // recieve answer to status query boost::asio::read(*tcpsock, recvbuf, boost::asio::transfer_at_least(1), errcode); if (errcode && errcode != boost::asio::error::eof) { std::cerr << "couldnt recieve status from " << ipstring << std::endl << errcode.message() << std::endl; keep_reading = false; continue; } // parse json recvjson = boost::asio::buffer_cast(recvbuf.data()); if (!reader->parse(recvjson, recvjson + recvbuf.size(), &root, &jsonerror)) { std::cerr << "couldnt parse recieved json" << std::endl << jsonerror << std::endl; keep_reading = false; continue; } // remove processed data from recvbuf recvbuf.consume(recvbuf.size()); // check if received answer to right query checkok = root["command"]; if(checkok.asString().compare("status") != 0) { std::cerr << "command check failed. client sent command \"status\"" << std::endl << "server replied to command \"" << checkok << "\"" << std::endl; keep_reading = false; continue; } else { std::cout << "server replied with status: " << root["response"] << std::endl; } break; } case CMD_DISCONNECT: { std::printf("disconnecting\n"); keep_reading = false; break; } default: { std::printf("unknown command %s\n", line); } case CMD_HELP: { std::printf("\n"); std::printf("AVAILABLE COMMANDS are:\n"); // printCmds(); std::printf("help - shows this help\n"); std::printf("status - asks the server for status\n"); std::printf("disconnect - closes the connection to the server\n"); break; } } std::printf("\n"); } free(line); return; }