void doSwitchMode(Mode mode){ arduino.connect(ip, port); if (mode != currentMode){ currentMode = mode; char data; switch (mode){ case Mode::SolidWhite: data = (char) 0; break; case Mode::Marquee: data = (char) 1; break; case Mode::ColorCycle: data = (char) 2; break; case Mode::Pew: data = (char) 3; break; default: break; } char* dataPointer = &data; arduino.send(dataPointer, sizeof(data)); } arduino.disconnect(); }
void Client::sendRegisteringToken(const std::string& name, const std::string& password, sf::TcpSocket& socket) { sf::Packet packet; packet << TransferType::REGISTERING << name << password; if(socket.send(packet) != sf::Socket::Done) throw std::runtime_error("sending packet failed."); // Receive the server response socket.receive(packet); TransferType response; packet >> response; switch(response) { case TransferType::USERNAME_NOT_AVAILABLE: throw std::runtime_error("the username " + name + " is not available."); case TransferType::FAILED_TO_REGISTER: throw std::runtime_error("the server failed to register your account."); case TransferType::ACKNOWLEDGE: return; default: throw std::runtime_error("unidentified server response."); } }
void ServerController::getAccountName(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string username, target, first, last; bool exists = false; packet >> username >> target; std::cout << "Attempting to find full name for User " << target << std::endl; // authenticate request if (checkAccount(username) == -1) { return; } int targetIndex = checkAccount(target); if (targetIndex != -1) { std::cout << "User does exist" << std::endl; first = data.accounts[targetIndex].getFirstName(); last = data.accounts[targetIndex].getLastName(); exists = true; response << exists << first << last; client.send(response); return; } std::cout << "User does not exist" << std::endl; response << exists; client.send(response); }
void ServerController::addMember(sf::Packet &packet, sf::TcpSocket &client, Account::AccessLevel level) { sf::Packet response; std::string username, conference, targetUser; packet >> username >> conference >> targetUser; bool success = false; int findIndex = checkAccount(username); int targetIndex = checkAccount(targetUser); int confIndex = checkConference(conference); if (findIndex == -1 || targetIndex == -1 || confIndex == -1) { success = false; response << success; client.send(response); return; } // add access to the conference in the target user's accessmap data.accounts[targetIndex].addAccess(conference, level); if (level == Account::Access_Reviewer) { data.conferences[confIndex].addReviewer(targetUser); } // add welcome notification to the user addNotification(targetUser, "Welcome to " + conference + "!"); success = true; response << success; client.send(response); data.saveAccounts(); data.saveConferences(); }
void ServerController::getLimit(sf::Packet &packet, sf::TcpSocket &client, const std::string &mode) { sf::Packet response; std::string username, conference; sf::Int16 limit; packet >> username >> conference >> limit; // authenticate request int accIndex = checkAccount(username); if (accIndex == -1) { return; } // authenticate conference int confIndex = checkConference(conference); if (confIndex == -1) { return; } if (mode == "ALLOCATED") { limit = data.conferences[confIndex].getMaxReviewedPapers(); } else if (mode == "PAPERREV") { limit = data.conferences[confIndex].getMaxPaperReviewers(); } response << limit; client.send(response); }
void ServerController::checkReviewed(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string user, conference, paper, first, last; packet >> user >> conference >> paper; // authenticate request int findIndex = checkAccount(user); if (findIndex != -1) { first = data.accounts[findIndex].getFirstName(); last = data.accounts[findIndex].getLastName(); } bool hasReviewed = false; for (int i = 0; i < (int)data.reviews.size(); ++i) { if (data.reviews[i].getTitle() == paper && data.reviews[i].getConference() == conference) { if (data.reviews[i].getPCMember() == (first + " " + last)) { hasReviewed = true; break; } } } response << hasReviewed; client.send(response); }
void ServerController::getReview(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string username, conf, id; Review aReview; bool found = false; packet >> username >> conf >> id; // authenticate request if (checkAccount(username) == -1) { return; } // authenticate conference if (checkConference(conf) == -1) { return; } // find review with id std::vector<Review>::iterator it; for (it = data.reviews.begin(); it != data.reviews.end(); ++it) { if (it->getReviewID() == id) { aReview = *it; found = true; break; } } response << found; if (found) { response << aReview; } client.send(response); }
void ServerController::getComments(sf::Packet &packet, sf::TcpSocket &client) { std::string conference, paperTitle; sf::Packet response; packet >> conference >> paperTitle; std::vector<Comment> comments; for (int i = 0; i < (int)data.submissions.size(); i++) { if (data.submissions[i].getConference() == conference) { if (data.submissions[i].getTitle() == paperTitle) { data.submissions[i].getComments(comments); } } } response << (int)comments.size(); for (int i = 0; i < (int)comments.size(); i++) { response << comments[i]; } client.send(response); }
void ServerController::getConfSubmissions(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string conference; std::vector<std::string> submission; packet >> conference; for (int i = 0; i < (int)data.submissions.size(); i++) { if(data.submissions[i].getConference() == conference) { submission.push_back(data.submissions[i].getTitle()); } } response << (int)submission.size(); for (int i = 0; i < (int)submission.size(); i++) { response << submission[i]; } client.send(response); }
void ServerController::checkPaperAlloc(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string conference, paperTitle; int rev_count; bool result = false; packet >> conference >> paperTitle; int confIndex = checkConference(conference); if(confIndex == -1) { return; } int max_rev = data.conferences[confIndex].getMaxPaperReviewers(); for (int i = 0; i < (int)data.submissions.size(); i++) { if (data.submissions[i].getConference() == conference) { if(data.submissions[i].getTitle() == paperTitle) { rev_count = data.submissions[i].getReviewerCount(); if (rev_count < max_rev) { result = true; break; } } } } response << result; client.send(response); }
void ServerController::getConferenceSubs(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string conf; packet >> conf; // add all matching submissions with this conference name std::vector<std::string> results; std::vector<Submission>::iterator it; for (it = data.submissions.begin(); it != data.submissions.end(); ++it) { if (it->getConference() == conf) { results.push_back(it->getTitle()); } } // pack into the response packet response << (int)results.size(); for (int i = 0; i < (int)results.size(); ++i) { response << results[i]; } client.send(response); }
void ServerController::loginAccount(sf::Packet &packet, sf::TcpSocket &client){ sf::Packet validate; std::string username, password; bool valid = false; packet >> username >> password; int findIndex = checkAccount(username,password); if (findIndex != -1) { valid = true; } if (valid) { // set the user as logged in data.accounts[findIndex].startSession(); data.addLog(username + " has logged in."); data.saveAccounts(); } validate << valid; client.send(validate); }
void ServerController::paperSubmission(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; Submission sub; bool exists = false; std::string username, conference, title; packet >> username; int findIndex = checkAccount(username); //get Account index if (findIndex == -1) { return; // ignore request if user is not found } packet >> sub; conference = sub.getConference(); title = sub.getTitle(); int confIndex = checkConference(conference); if (confIndex == -1) { return; // ignore request if conference is not found } if (data.accounts[findIndex].getAccess(conference) < Account::Access_Author) { return; // ignore request if user is not at least an author of that conference } // check conference is in submission phase if (data.conferences[confIndex].getCurrentPhase() != "Submission") { return; // ignore request if conference is not accepting submissions } // check that the paper does not already exist if (checkSubmission(title, conference) == -1) { // set the papers university to the submitting author sub.setUniversity(data.accounts[findIndex].getUniversity()); // add the submitting author as an author std::string firstname = data.accounts[findIndex].getFirstName(); std::string lastname = data.accounts[findIndex].getLastName(); sub.addAuthor(firstname, lastname); data.submissions.push_back(sub); data.saveSubmissions(); data.addLog("Paper was submitted: " + title + " by " + username + " for conference " + conference); addNotification(username, "You submitted a paper '" + title + "' to " + conference); notifyConference(conference, username + " submitted a paper '" + title + "' to " + conference, Account::Access_Chairman); } else { exists = true; } response << exists; client.send(response); }
void Player::sync(sf::TcpSocket & socket) { if (mEntity) { sf::Packet packet; packet << Cl::GameEvent << GameEvent::MoveEntity << mEntity->getID() << mEntity->getPosition().x << mEntity->getPosition().y; socket.send(packet); packet.clear(); packet << Cl::GameEvent << GameEvent::RotateEntity << mEntity->getID() << mEntity->getRotation(); socket.send(packet); if (mSkill1) { if (mEntity->getType() == Entity::Type::Human) { sf::Packet packet; packet << Cl::GameEvent << GameEvent::ShootBullet <<mEntity->getID() << mEntity->getRotation() << mEntity->getCenter().x << mEntity->getCenter().y; socket.send(packet); } else if (mEntity->getType() == Entity::Type::Zombie) { std::cout << "Zombie melee attack\n"; sf::Packet packet; packet << Cl::GameEvent << GameEvent::ZombieMeleeAttack; Zombie * z = static_cast<Zombie*>(mEntity); sf::FloatRect rect = z->getMeeleAttackBox(); packet << rect.top << rect.left << rect.width << rect.height; std::cout << rect.top << ", " << rect.left << ", " << rect.width << ". " << rect.height << "\n"; socket.send(packet); } } } }
void recv_dummy_or_inc_ctr() { std::size_t dummy; if(_sckt.receive(&dummy, 0, dummy) == sf::Socket::Disconnected) { _ctr += 1; } else { reset_ctr(); } }
void update() { if(!busy) { ssvu::lo("ManagedSocket") << "Update failed - not busy" << std::endl; return; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); sf::Packet packet; for(int i{0}; i < 5; ++i) { if(busy && socket.receive(packet) == sf::Socket::Done) onPacketReceived(packet); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } }
sf::Socket::Status NETSERVER::receiveTime(sf::TcpSocket &p_socket, char* p_buffer, const unsigned int p_limit, size_t &p_received) { sf::SocketSelector selector; selector.add(p_socket); if (selector.wait(sf::seconds(2))) { return p_socket.receive(p_buffer, p_limit, p_received); } else { return sf::Socket::NotReady; } } // receiveTime()
bool trySendPacket(sf::Packet mPacket) { if(!busy) { ssvu::lo("ManagedSocket") << "Couldn't send packet - not busy" << std::endl; return false; } for(int i{0}; i < 5; ++i) { if(busy && socket.send(mPacket) == sf::Socket::Done) { onPacketSent(mPacket); return true; } std::this_thread::sleep_for(std::chrono::milliseconds(50)); } ssvu::lo("ManagedSocket") << "Couldn't send packet - disconnecting" << std::endl; disconnect(); return false; }
// Tell the newly connected peer about how the world is currently void GameServer::informWorldState(sf::TcpSocket& socket) { sf::Packet packet; packet << static_cast<sf::Int32>(Server::InitialState); packet << mWorldHeight << mBattleFieldRect.top + mBattleFieldRect.height; packet << static_cast<sf::Int32>(mAircraftCount); for (std::size_t i = 0; i < mConnectedPlayers; ++i) { if (mPeers[i]->ready) { for(sf::Int32 identifier : mPeers[i]->aircraftIdentifiers) packet << identifier << mAircraftInfo[identifier].position.x << mAircraftInfo[identifier].position.y << mAircraftInfo[identifier].hitpoints << mAircraftInfo[identifier].missileAmmo; } } socket.send(packet); }
bool ServerController::registerAccount(sf::Packet &packet, sf::TcpSocket &client){ sf::Packet existsPacket; std::string username,password,email,university, firstname, lastname; std::vector<std::string> keywords; int keywordSize = 0; packet >> username >> password >> firstname >> lastname >> email >> university >> keywordSize; std::string tmpkeyword; for (int i = 0; i < keywordSize; ++i) { packet >> tmpkeyword; keywords.push_back(tmpkeyword); } bool exists = false; int index = checkAccount(username); if (index == -1) { data.addLog("New user registered! Welcome " + username); Account tmp; tmp.setUsername(username); tmp.setPassword(password); tmp.setFirstName(firstname); tmp.setLastName(lastname); tmp.setEmail(email); tmp.setUniversity(university); for (int i = 0; i < keywordSize; ++i) { tmp.addKeyword(keywords[i]); } // registered users start logged in tmp.startSession(); data.accounts.push_back(tmp); data.saveAccounts(); } else { exists = true; } existsPacket << exists; client.send(existsPacket); }
void ServerController::getFreeReviewers(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string conference; std::vector<std::string> reviewerList; std::vector<std::string> freeList; packet >> conference; int confIndex = checkConference(conference); if (confIndex == -1) { return; } data.conferences[confIndex].getReviewers(reviewerList); int maxReviewers = data.conferences[confIndex].getMaxPaperReviewers(); std::cout << "Getting a list of free reviewers for conference " << conference << std::endl; for (int i = 0; i < (int)reviewerList.size(); i++) { int findIndex = checkAccount(reviewerList[i]); if (findIndex != -1) { std::cout << "Displaying Reviewers: " << reviewerList[i] << std::endl; if (data.accounts[findIndex].checkAllocation(conference, maxReviewers)) { std::cout << "Pushing" << std::endl; freeList.push_back(reviewerList[i]); } } } response << (int)freeList.size(); for (int i = 0; i < (int)freeList.size(); i++) { response << freeList[i]; } client.send(response); }
void ServerController::getFinalReview(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string username, conference, paper; std::string finalRev; bool exists = false; packet >> username >> conference >> paper; // authenticate request int accIndex = checkAccount(username); if (accIndex == -1) { return; } // authenticate conference int confIndex = checkConference(conference); if (confIndex == -1) { return; } if (data.accounts[accIndex].getAccess(conference)) { for (int i = 0; i < (int)data.reviews.size(); ++i) { if (data.reviews[i].getConference() == conference && data.reviews[i].getTitle() == paper && data.reviews[i].getFinal()) { finalRev = data.reviews[i].getReviewID(); exists = true; break; } } response << exists << finalRev; } else { response << exists; } client.send(response); }
inline bool connect(sf::IpAddress mIp, unsigned short mPort) { if(busy) { ssvu::lo("ManagedSocket") << "Error: already connected" << std::endl; return false; } for(int i{0}; i < 5; ++i) { if(!busy && socket.connect(mIp, mPort) == sf::Socket::Done) goto succeed; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } return false; succeed: if(!busy) { ssvu::lo("ManagedSocket") << "Connecting..." << std::endl; busy = true; handlerFuture = std::async(std::launch::async, [this]{ while(busy) update(); }); } ssvu::lo("ManagedSocket") << "Connected to " << mIp.toString() << ":" << mPort << std::endl; return true; }
void ServerController::sendSubDetail(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string conf, paperTitle; packet >> conf >> paperTitle; int confIndex = checkConference(conf); if (confIndex == -1) { return; // ignore request if conference is not found } int subIndex = checkSubmission(paperTitle, conf); if (subIndex == -1) { return; // ignore request if paper is not found } Submission result = data.submissions[subIndex]; response << result; client.send(response); }
////////////////////////////////////////////////////////// //======================================================// // Accept // //======================================================// // This will attempt to accept a connection from a // // tcp socket. // ////////////////////////////////////////////////////////// bool Connection::Accept(sf::TcpSocket& client_socket) { // If we have successfully accepted a connection from the client. if (connection_listener_.accept(client_socket) == sf::Socket::Done) { // Print out the IP address of the connecting client. std::cout << "Client connected from: " << client_socket.getRemoteAddress() << std::endl; // We have accepted a connection from this client, notify the server. return true; } // We can modify what the standard response for not connecting with a client is here. // Without having to go through network connecting code and modifying each if statement to provide a standard response. // ERROR: Could not accept a connection on the server. DisplayErrorMessage(kConnectionErrorMessage); // We have not accepted the connection from this client. return false; }
void ServerController::getReviewers(sf::Packet &packet, sf::TcpSocket &client) { sf::Packet response; std::string username, conference; std::vector<std::string> reviewer; packet >> username >> conference; int confIndex = checkConference(conference); if(confIndex == -1) { return; } data.conferences[confIndex].getReviewers(reviewer); response << (int)reviewer.size(); for (int i = 0; i < (int)reviewer.size(); i++) { response << reviewer[i]; } client.send(response); }
bfbc2::server_info bfbc2::QueryServerInfo(sf::TcpSocket &socket) { server_info serverInfo; std::cout << "Sending serverInfo query..." << std::endl; if (socket.send(serverInfo_QueryPacket, sizeof(serverInfo_QueryPacket)) == sf::Socket::Status::Done) { std::cout << "Success! Waiting for response..." << std::endl; char buffer[PACKETSIZE]; std::size_t received = 0; // receive response if (socket.receive(buffer, sizeof(buffer), received) == sf::Socket::Status::Done) { if (received > 0) { std::cout << "Success! Processing..." << std::endl; // skip header. int index = 8; // get number of WORDs in packet, then store them for parsing. uint32_t numofwords = (static_cast<uint32_t>(buffer[index]) ) + (static_cast<uint32_t>(buffer[index + 1]) << 8) + (static_cast<uint32_t>(buffer[index + 2]) << 16) + (static_cast<uint32_t>(buffer[index + 3]) << 24); // skip numwords index += 4; // extract the content of each word. std::vector<std::string> content; for (uint32_t i = 0; i < numofwords; i++) { content.push_back(GetWordContent(buffer, index)); } // checks to see if we have the correct results if (!content.empty() && content.size() == 24) { // // CHECKING FOR OK RESPONSE (.at(0)) & & IF ACCEPTINGPLAYERS ) // if (content.at(0) == "OK") { if (content.at(12) == "AcceptingPlayers") { serverInfo.ip = socket.getRemoteAddress(); serverInfo.name = content.at(1); serverInfo.playersonline = atoi(content.at(2).c_str()); serverInfo.maxplayers = atoi(content.at(3).c_str()); serverInfo.gamemode = content.at(4); std::string mapstring = content.at(5); // change map string to lowercase, as the map filename is stored in the server .cfg, // and the server admin can make it upper or lower case. std::transform(mapstring.begin(), mapstring.end(), mapstring.begin(), ::tolower); std::string map; if (mapstring.find("001") != std::string::npos) { map = "Panama Canal"; } else if (mapstring.find("mp_002") != std::string::npos) { map = "Valparaiso"; } else if (mapstring.find("003") != std::string::npos) { map = "Laguna Alta"; } else if (mapstring.find("004") != std::string::npos) { map = "Isla Inocentes"; } else if (mapstring.find("mp_005") != std::string::npos) { map = "Atacama Desert"; } else if (mapstring.find("006") != std::string::npos) { map = "Arica Harbor"; } else if (mapstring.find("007") != std::string::npos) { map = "White Pass"; } else if (mapstring.find("008") != std::string::npos) { map = "Nelson Bay"; } else if (mapstring.find("009") != std::string::npos) { map = "Laguna Presa"; } else if (mapstring.find("012") != std::string::npos) { map = "Port Valdez"; } else if (mapstring.find("oasis") != std::string::npos) { map = "Oasis"; } else if (mapstring.find("sp_005") != std::string::npos) { map = "Heavy Metal"; } else if (mapstring.find("sp_002") != std::string::npos) { map = "Cold War"; } else if (mapstring.find("harvest") != std::string::npos) { map = "Harvest Day"; } serverInfo.map = map; } } } } } // socket.receive } // socket.send // if send, receive, or content check fails anywhere, server_info.ip will return sf::IpAddress::None return serverInfo; }
std::vector<bfbc2::player_info> bfbc2::QueryPlayerInfo(sf::TcpSocket &socket) { std::cout << "Sending playerInfo query..." << std::endl; std::vector<player_info> players; if (socket.send(listPlayer_QueryPacket, sizeof(listPlayer_QueryPacket)) == sf::Socket::Status::Done) { std::cout << "Success! Waiting for response..." << std::endl; char buffer[PACKETSIZE]; std::size_t received = 0; // receive response if (socket.receive(buffer, sizeof(buffer), received) == sf::Socket::Status::Done) { if (received > 0) { std::cout << "Success! Processing..." << std::endl; // skip header int index = 8; uint32_t numofwords = (static_cast<uint32_t>(buffer[index]) ) + (static_cast<uint32_t>(buffer[index + 1]) << 8) + (static_cast<uint32_t>(buffer[index + 2]) << 16) + (static_cast<uint32_t>(buffer[index + 3]) << 24); // skip numofwords index += 4; // extract the content of each word. std::vector<std::string> content; for (uint32_t i = 0; i < numofwords; i++) { content.push_back(GetWordContent(buffer, index)); } // hIndex is used for parsing. int hIndex = 0; // check for content. we need at least 9 entries for the // response and the categories, so if it didn't at least fill those, // i'll know there was a kind of error. if (content.at(hIndex) == "OK" && content.size() >= 9) { // skip forward +2, 1 for response, other for numofcategories // i know the number, so no need to pull. hIndex += 2; // next is the actual categories, 9 of them. // skipping & not parsing the category names, already know them. hIndex += 9; // next is the player count on the server, read then skip int playerc = atoi(content.at(hIndex).c_str()); hIndex++; // parse players and their category info for (int pc = 0; pc < playerc; pc++) { player_info p; p.clantag = content.at(hIndex++); p.name = content.at(hIndex++); p.guid = content.at(hIndex++); p.teamid = atoi(content.at(hIndex++).c_str()); p.squadid = atoi(content.at(hIndex++).c_str()); p.kills = atoi(content.at(hIndex++).c_str()); p.deaths = atoi(content.at(hIndex++).c_str()); p.score = atoi(content.at(hIndex++).c_str()); p.ping = atoi(content.at(hIndex++).c_str()); players.push_back(p); } } } } // socket.receive } // socket.send return players; }
ManagedSocket() { socket.setBlocking(false); }
inline void disconnect() { socket.disconnect(); busy = false; }