void GameStateManager::handlePlayerMove(int32_t eid) { const PlayerState & player = *m_states[eid]; sendRawToAllExceptOne(rawPacketSCEntityTeleport(eid, getFractionalCoords(player.position), player.yaw, player.pitch), eid); auto interesting_blocks = m_map.blockAlerts().equal_range(getWorldCoords(player.position)); for (auto it = interesting_blocks.first; it != interesting_blocks.second; ++it) { if (it->second.type == Map::BlockAlert::CONTAINS_SPAWN_ITEM) { const auto jt = m_map.items().find(it->second.data); if (jt != m_map.items().end()) { sendToAll(MAKE_CALLBACK(packetSCCollectItem, jt->first, eid)); sendToAll(MAKE_CALLBACK(packetSCDestroyEntity, jt->first)); // Add 1 undamaged unit to the player's inventory. updatePlayerInventory(eid, jt->second, 1, 0); m_map.items().erase(jt); } } } }
void GameServer::tick() { updateClientState(); // Check for mission success = all planes with position.y < offset bool allAircraftsDone = true; for(auto pair : mAircraftInfo) { // As long as one player has not crossed the finish line yet, set variable to false if (pair.second.position.y > 0.f) allAircraftsDone = false; } if (allAircraftsDone) { sf::Packet missionSuccessPacket; missionSuccessPacket << static_cast<sf::Int32>(Server::MissionSuccess); sendToAll(missionSuccessPacket); } // Remove IDs of aircraft that have been destroyed (relevant if a client has two, and loses one) for (auto itr = mAircraftInfo.begin(); itr != mAircraftInfo.end(); ) { if (itr->second.hitpoints <= 0) mAircraftInfo.erase(itr++); else ++itr; } // Check if its time to attempt to spawn enemies if (now() >= mTimeForNextSpawn + mLastSpawnTime) { // No more enemies are spawned near the end if (mBattleFieldRect.top > 600.f) { std::size_t enemyCount = 1u + randomInt(2); float spawnCenter = static_cast<float>(randomInt(500) - 250); // In case only one enemy is being spawned, it appears directly at the spawnCenter float planeDistance = 0.f; float nextSpawnPosition = spawnCenter; // In case there are two enemies being spawned together, each is spawned at each side of the spawnCenter, with a minimum distance if (enemyCount == 2) { planeDistance = static_cast<float>(150 + randomInt(250)); nextSpawnPosition = spawnCenter - planeDistance / 2.f; } // Send the spawn orders to all clients for (std::size_t i = 0; i < enemyCount; ++i) { sf::Packet packet; packet << static_cast<sf::Int32>(Server::SpawnEnemy); packet << static_cast<sf::Int32>(1 + randomInt(Aircraft::TypeCount-1)); packet << mWorldHeight - mBattleFieldRect.top + 500; packet << nextSpawnPosition; nextSpawnPosition += planeDistance / 2.f; sendToAll(packet); } mLastSpawnTime = now(); mTimeForNextSpawn = sf::milliseconds(2000 + randomInt(6000)); } } }
void Epoll::actionEnter(Client *me, Json::Value &obj) { int uid = obj["uid"].asInt(); std::map<int, Client*>::iterator exists_user; exists_user = _users.find(uid); if (exists_user != _users.end() && exists_user->second != me) { std::cout << "uid:" << uid << " exists, take it out!\n"; takeoutClient(exists_user->second); } me->setName(obj["data"].asString()); me->setUID(uid); addUser(me); std::cout << me->getName() << "上线!" << std::endl; Json::Value user; user["uid"] = uid; user["id"] = me->getFileDescripto(); user["name"] = me->getName(); Json::Value data; data["user"] = user; data["list"] = getJsonClientList(); Json::Value oops; oops["code"] = Message::sEnter; oops["data"] = data; sendToAll(oops.toStyledString()); }
void refreshStyle(void) { if (false == engine_running) return; readStyle(); setmetrics(); sendToAll(MSGID_REFRESH); }
// Fonction de gestion de deconnexion void sort(ListeJoueurs *liste, Joueur *myJoueur) { char buf[TBUF]; sprintf(buf, "DECONNEXION/%s/\n", myJoueur->pseudo); suppJoueurListe(liste, myJoueur); detruire_joueur(myJoueur); sendToAll(buf, liste, NULL, 1); }
void mpeServerTCP::reset() { currentFrame = 0; shouldTriggerFrame = false; sendToAll("R"); }
void GameServer::handleDisconnections() { for (auto itr = mPeers.begin(); itr != mPeers.end(); ) { if ((*itr)->timedOut) { // Inform everyone of the disconnection, erase for (sf::Int32 identifier : (*itr)->aircraftIdentifiers) { sendToAll(sf::Packet() << static_cast<sf::Int32>(Server::PlayerDisconnect) << identifier); mAircraftInfo.erase(identifier); } mConnectedPlayers--; mAircraftCount -= (*itr)->aircraftIdentifiers.size(); itr = mPeers.erase(itr); // Go back to a listening state if needed if (mConnectedPlayers < mMaxConnectedPlayers) { mPeers.push_back(PeerPtr(new RemotePeer())); setListening(true); } broadcastMessage("An ally has disconnected."); } else { ++itr; } } }
// Fonction de gestion lors de la connexion Joueur *connex(int sock, ListeJoueurs *liste) { char buf[TBUF]; char *pseudo = strtok(NULL, "/"); pthread_mutex_lock(&(liste->mutex)); if(pseudo_deja_present(liste, pseudo)) { pthread_mutex_unlock(&(liste->mutex)); printf("[Pseudo deja present] %s\n", pseudo); return NULL; } pthread_mutex_unlock(&(liste->mutex)); Joueur *myJoueur = create_joueur(pseudo, sock); addJoueurListe(liste, myJoueur); /* Validation de la connexion a user */ sprintf(buf, "BIENVENUE/%s/\n", pseudoJoueur(myJoueur)); sendTo(buf, liste, myJoueur, 1); /// sprintf(buf, "COMPATIBLEAFFICHAGE/\n"); sendTo(buf, liste, myJoueur, 1); // Pour dire que le serveur effectue un temps d'affichage /* Signalement connexion user aux autres joueurs */ sprintf(buf, "CONNECTE/%s/\n", pseudoJoueur(myJoueur)); sendToAll(buf, liste, myJoueur, 1); // All sauf myJoueur return myJoueur; }
void handleInput(char *comm, size_t size) { if (strncmp(comm, "ECHO", 4) == 0) { sendEcho(comm, size - 5); } else if (strncmp(comm, "LIST", 4) == 0) { sendList(); } else if (strncmp(comm, "2ALL", 4) == 0) { sendToAll(comm, size - 5); } else if (strncmp(comm, "2ONE", 4) == 0) { strtok(comm, " "); char *str = strtok(comm + 5, " "); if (str == NULL) { fprintf(stderr, "Wrong number of arguments\n"); return; } int id = atoi(str); str = strtok(NULL, " "); size_t size = 0; if (str != NULL) size = strlen(str); sendToOne(str, id, size); } else if (strncmp(comm, "FRIENDS", 7) == 0) { sendFriends(comm, size - 8); } else if (strncmp(comm, "ADD", 3) == 0) { sendAddFriends(comm, size - 4); } else if (strncmp(comm, "DEL", 3) == 0) { sendDelFriends(comm, size - 4); } else if (strncmp(comm, "2FRIENDS", 8) == 0) { sendToFriends(comm, size - 9); } else if (strncmp(comm, "STOP", 4) == 0) { exit(0); } else { printf("Wrong command -> %s\n", comm); } }
void GameStateManager::reactToBlockDestruction(const WorldCoords & wc) { // Clear the block alerts. The only alerts that can possibly be // stored with a solid block are of the type that we process here, // so we clear the entire range. auto interesting_blocks = m_map.blockAlerts().equal_range(wc); m_map.blockAlerts().erase(interesting_blocks.first, interesting_blocks.second); // Remove attached torches. WorldCoords wn; for (size_t k = 1; k < 6; ++k) { const WorldCoords wn = wc + Direction(k); if (!m_map.haveChunk(getChunkCoords(wn))) continue; unsigned char & block = m_map.chunk(getChunkCoords(wn)).blockType(getLocalCoords(wn)); if (block == BLOCK_Torch) { sendToAll(MAKE_CALLBACK(packetSCBlockChange, wn, BLOCK_Air, 0)); block = BLOCK_Air; m_map.chunk(getChunkCoords(wn)).taint(); reactToSuccessfulDig(wn, EBlockItem(block)); } } }
void ServerImpl::onClientDisconnected(CL_NetGameConnection *p_netGameConnection) { cl_log_event( LOG_EVENT, "player %1 disconnects", m_connections[p_netGameConnection].m_name.empty() ? CL_StringHelp::uint_to_local8((unsigned) p_netGameConnection) : m_connections[p_netGameConnection].m_name ); std::map<CL_NetGameConnection*, Player>::iterator itor = m_connections.find(p_netGameConnection); if (itor != m_connections.end()) { const Player &player = itor->second; // emit the signal if player was in the game if (player.m_gameStateSent) { INVOKE_1(playerLeft, player.m_name); } // send event to rest of players PlayerLeft playerLeft; playerLeft.setName(player.m_name);; sendToAll(playerLeft.buildEvent(), itor->first); // cleanup m_connections.erase(itor); } }
/* * Funktion schliesst alle verwendeten Ressourcen und * beendet den Server */ void endServer(){ debugPrint("Beende Server."); // Nachricht an alle Clients senden - sofern welche angemeldet debugPrint("Sende Nachricht an Clients: Server wird beendet."); if(countUser() > 0){ PACKET close_server_packet; close_server_packet.header.type = RFC_ERRORWARNING; close_server_packet.header.length = htons(sizeof(ERROR)); //close_server_packet.content.error.errortype = ERR_SERVER_CLOSE; close_server_packet.content.error.errortype = ERR_FATAL; strncpy(close_server_packet.content.error.errormessage, "Server beendet", 100); // sende Nachricht sendToAll(close_server_packet); debugPrint("Nachricht ueber Serverende an alle Clients verschickt."); } // Socket schliessen if(close(server_socket) == 0){ debugPrint("Serversocket geschlossen."); } else { debugPrint("Konnte Serversocket nicht schliessen."); } // shared memorey // aus Adressraum entfernen munmap(shmData, shmLen); // Filedeskritpor SharedMemory schliessen close(shmHandle); // SharedMemory Objekt entfernen shm_unlink(SHMEM_NAME); debugPrint("Shared Memory entfernt."); // loader beenden if(kill(forkResult, SIGINT) == 0){ debugPrint("Loaderprozess beendet."); } else { debugPrint("Loaderprozess konnte nicht beendet werden."); } // SingleInstance-Datei schliessen und loeschen closeSingleInstance(SingleInstanceFile); if(remove("serverInstancePIDFile") == 0){ debugPrint("SingleInstanceFile geschlossen und geloescht."); } else { debugPrint("Konnte SingleInstanceFile nicht loeschen."); } infoPrint("bye ..."); exit(0); }
void GameServer::updateClientState() { sf::Packet updateClientStatePacket; updateClientStatePacket << static_cast<sf::Int32>(Server::UpdateClientState); updateClientStatePacket << static_cast<float>(mBattleFieldRect.top + mBattleFieldRect.height); updateClientStatePacket << static_cast<sf::Int32>(mAircraftInfo.size()); for(auto aircraft : mAircraftInfo) updateClientStatePacket << aircraft.first << aircraft.second.position.x << aircraft.second.position.y; sendToAll(updateClientStatePacket); }
// CHAT/user/msg/ // Fonction de gestion du chat void chat(Session *s, Joueur *myJoueur) { char buf[TBUF]; char *message; strtok(NULL, "/"); /* Le nom */ message = strtok(NULL, "/"); if(message == NULL) sprintf(buf, "CHAT/%s//\n", pseudoJoueur(myJoueur)); else sprintf(buf, "CHAT/%s/%s/\n", pseudoJoueur(myJoueur), message); sendToAll(buf, s->liste, myJoueur, 1); }
void GameStateManager::reactToToggle(const WorldCoords & wc, EBlockItem b) { if (!m_map.haveChunk(getChunkCoords(wc))) return; Chunk & chunk = m_map.chunk(getChunkCoords(wc)); switch (b) { case BLOCK_WoodenDoor: case BLOCK_IronDoor: { // We don't really care if the door is one, two or three blocks tall, // but we'll only treat at most one block above and below the clicked one. uint8_t meta = chunk.getBlockMetaData(getLocalCoords(wc)); meta ^= 0x4; chunk.setBlockMetaData(getLocalCoords(wc), meta); sendToAll(MAKE_CALLBACK(packetSCBlockChange, wc, b, meta)); if (wY(wc) < 127 && chunk.blockType(getLocalCoords(wc + BLOCK_YPLUS)) == b) { uint8_t meta = chunk.getBlockMetaData(getLocalCoords(wc + BLOCK_YPLUS)); meta ^= 0x4; chunk.setBlockMetaData(getLocalCoords(wc + BLOCK_YPLUS), meta); sendToAll(MAKE_CALLBACK(packetSCBlockChange, wc + BLOCK_YPLUS, b, meta)); } if (wY(wc) > 0 && chunk.blockType(getLocalCoords(wc + BLOCK_YMINUS)) == b) { uint8_t meta = chunk.getBlockMetaData(getLocalCoords(wc + BLOCK_YMINUS)); meta ^= 0x4; chunk.setBlockMetaData(getLocalCoords(wc + BLOCK_YMINUS), meta); sendToAll(MAKE_CALLBACK(packetSCBlockChange, wc + BLOCK_YMINUS, b, meta)); } break; } default: break; } }
void GameStateManager::reactToSuccessfulDig(const WorldCoords & wc, EBlockItem block_type) { // this is just temporary std::cout << "Successfully dug at " << wc << " for " << BLOCKITEM_INFO.find(block_type)->second.name << std::endl; if (block_type == BLOCK_WoodenDoor || block_type == BLOCK_IronDoor) { Chunk & chunk = m_map.chunk(getChunkCoords(wc)); if (wY(wc) < 127 && chunk.blockType(getLocalCoords(wc + BLOCK_YPLUS)) == block_type) { sendToAll(MAKE_CALLBACK(packetSCBlockChange, wc + BLOCK_YPLUS, BLOCK_Air, 0)); chunk.blockType(getLocalCoords(wc + BLOCK_YPLUS)) = BLOCK_Air; } if (wY(wc) > 0 && chunk.blockType(getLocalCoords(wc + BLOCK_YMINUS)) == block_type) { sendToAll(MAKE_CALLBACK(packetSCBlockChange, wc + BLOCK_YMINUS, BLOCK_Air, 0)); chunk.blockType(getLocalCoords(wc + BLOCK_YMINUS)) = BLOCK_Air; } spawnSomething(block_type == BLOCK_WoodenDoor ? ITEM_WoodenDoor : ITEM_IronDoor, 1, 0, wc); } else if (block_type != 0) { spawnSomething(uint16_t(block_type), 1, 0, wc); auto interesting_blocks = m_map.blockAlerts().equal_range(wc); for (auto it = interesting_blocks.first; it != interesting_blocks.second; ++it) { if (it->second.type == Map::BlockAlert::SUPPORTS_CANDLE) { reactToBlockDestruction(wc); break; } } } }
void serverStateClass::playerClickedTo(sf::Packet& packet, typePlayer thisPlayer) { sf::Packet newPacket; sf::Uint8 x; sf::Uint8 y; packet >> x >> y; server.clickTo(x, y, &newPacket, thisPlayer); if(newPacket.getDataSize() != 0) { sendToAll(newPacket); } }
void Epoll::actionChat(Client* me, Json::Value &obj){ Json::Value user; user["uid"] = me->getUID(); user["name"] = me->getName(); Json::Value data; data["user"] = user; data["content"] = obj["data"]["content"].asString(); Json::Value oops; oops["code"] = Message::sChat; oops["data"] = data; sendToAll(oops.toStyledString()); }
void stopEngine(void) { //dbg_printf("Stopped skinner engine"); if (false == engine_running) return; sendToAll(MSGID_UNLOAD); EntryFunc(ENGINE_UNSETHOOKS, lpvMem); free_exclusion_list(); free_dll(); // restore the normal SystemParameter settings, window metrics, etc. SystemParametersInfo(SPI_SETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm_save, SPIF_SENDCHANGE); // restore sys-colors setTTC(RESTORE_3DC); engine_running = false; }
void GameStateManager::spawnSomething(uint16_t type, uint8_t number, uint8_t damage, const WorldCoords & wc) { WorldCoords wbelow(wc); if (!fall(wbelow)) return; int32_t eid = GenerateEID(); m_map.blockAlerts().insert(std::make_pair(wbelow, Map::BlockAlert(Map::BlockAlert::CONTAINS_SPAWN_ITEM, eid))); m_map.items().insert(std::make_pair(eid, type)); // stub sendToAll(MAKE_CALLBACK(packetSCPickupSpawn, eid, type, number, damage, wc)); }
void ServerImpl::onCarState( CL_NetGameConnection *p_conn, const CL_NetGameEvent &p_event) { // register last car state Player &player = m_connections[p_conn]; player.m_lastCarState.parseEvent(p_event); // set players name (client may not set it to his nickname) player.m_lastCarState.setName(player.m_name); // send it all over sendToAll(player.m_lastCarState.buildEvent(), p_conn); }
void ChatAgent::processInput(PPtr<KString> input) { if(_nickName.empty()) { _nickName = input->toUtf8String(); _pConsole.print("You shall be known as \"" + _nickName + "\"."); _pConsole.print("Type anything to send. Enter \"quit\" to finish."); } else if(input->equals("quit")) { _pConsole.print("Bye!"); quit(); } else { Ptr<KRecord> message = new KRecord(message_t()); message->getString(MESSAGE_T_SENDER)->set(_nickName); message->getString(MESSAGE_T_CONTENT)->set(input.AS(KValue)); sendToAll(OP_MESSAGE, message.AS(KValue)); } }
void Epoll::actionMove(Client* me, Json::Value &obj){ Json::Value user; user["uid"] = me->getUID(); user["name"] = me->getName(); Json::Value data; data = obj["data"]; data["user"] = user; //data['x'] = obj["data"]["x"].asFloat(); //data['y'] = obj["data"]["y"].asFloat(); Json::Value oops; oops["code"] = Message::sMove; oops["data"] = data; sendToAll(oops.toStyledString()); }
void ServerImpl::onVoteTick( CL_NetGameConnection *p_conn, const CL_NetGameEvent &p_event ) { VoteTick voteTick; voteTick.parseEvent(p_event); if (!m_voteSystem.isFinished()) { const bool accepted = m_voteSystem.addVote(voteTick.getOption(), (int) p_conn); if (accepted && !m_voteSystem.isFinished()) { // send this vote over network sendToAll(p_event); } } }
void startEngine(void) { //dbg_printf("Started skinner engine"); readSettings(); set_log_window(); if (engine_running) return; if (false == make_exclusion_list()) return; if (false == load_dll()) { free_exclusion_list(); return; } bbSkinMsg = RegisterWindowMessage(BBLEANSKIN_WINDOWMSG); // save sys-colors setTTC(SAVE_3DC); // save the normal SystemParameter settings, window metrics, etc. ncm_save.cbSize = sizeof(NONCLIENTMETRICS); SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof ncm_save, &ncm_save, 0); ZeroMemory(&ncm_prev, sizeof(NONCLIENTMETRICS)); // read styles for skin readStyle(); // possibly set sys-colors setTTC(APPLY_3DC); // set the system wide window metrics according to style metrics setmetrics(); // set the hook EntryFunc(ENGINE_SETHOOKS, lpvMem); engine_running = true; // now apply to open windows if (applyToOpen) sendToAll(MSGID_LOAD); //write_bin(); }
void ServerImpl::onVoteSystemFinished() { // voting finished, send event VoteEnd voteEnd; voteEnd.setResult(m_voteSystem.getResult()); sendToAll(voteEnd.buildEvent()); // check if I should take action if (m_voteSystem.getResult() == VOTE_PASSED) { switch (m_voteSystem.getType()) { case VOTE_RESTART_RACE: startRace(); break; default: assert(0 && "unknown VoteType"); } } }
void Epoll::delClient(Client* client) { Json::Value oops,data,user; user["uid"] = client->getUID(); user["name"] = client->getName(); if (user["uid"] == 0) { oops["code"] = Message::sTakeOut; client->send(oops.toStyledString()); } _clients.erase(_clients.find(client->getFileDescripto())); delete client; if (user["uid"] > 0) { oops["code"] = Message::sLeave; _users.erase(_users.find(user["uid"].asInt())); data["user"] = user; data["list"] = getJsonClientList(); oops["data"] = data; sendToAll(oops.toStyledString()); } }
void routine(std::string direccion,int conexiones) { //Creamos el socket de dispatching para saber cuando se nos conectan TCPSpcket dispatchSock; SocketAddress addressReceive; addressReceive.SetAddress(direccion); dispatchSock.Bind(addressReceive); std::vector<std::shared_ptr<TCPSpcket>> clientList; dispatchSock.Listen(conexiones); SocketAddress comesFrom; for (int i = 0; i < conexiones; i++) { clientList.push_back(dispatchSock.Accept(comesFrom)); } sendToAll(clientList,"BEGIN",conexiones); }
void Client::setNick(std::string const& newNick, Context & context) { Context::ListClient::W ptrLC(context.m_listClient); std::cerr << (*ptrLC)[newNick] << std::endl;// WTF? Writing in std::cerr, is there is an error here? if( (*ptrLC)[newNick] ) { sendMessage( ":"+context.m_serverName + " " + IRC::ERR_NICKNAMEINUSE + " * " + newNick + " :Nickname is already in use.\r\n" ); return; } //TODO vérifier dans BDD if( ! m_right.connect ) { if(!m_nick.empty()) { CST<std::string>::W ptr(m_variableNick); ptrLC->remove(*ptr); } m_nick = newNick; if(!m_info.empty()) { m_info = m_nick + m_info; m_right.connect = true; sendMessage(IRC::buildMOTD(context, *this)); } } else { CST<std::string>::W ptr(m_variableNick); ptrLC->remove(*ptr); *ptr = newNick; std::string msg = ":" + m_info + "@" + context.m_serverName + " NICK :" + newNick + "\r\n"; m_info = newNick + "!~" + m_userName; // TODO SF ? //leave + join -> modérateurs pour anonymat sendToAll(msg); sendMessage(msg); } ptrLC->add(newNick, this); }
//FONCTION : réagit selon le message passé en paramètre void Server::processRequest(const QString &message,QTcpSocket*socket) { QStringList req = message.split(QRegExp("@")); int idClient = getIndexFromSocket(socket); if(req[0].compare("isSending")==0) { bool statePlaying=req[1].toInt(); qDebug() << "SERVER pipeline will change because user streaming stopped"; clients[idClient].isSending=statePlaying; setPipeline(); } else if (req[0].compare("name")==0) { int databaseResult = verifyDataBase(req[1],req[2]); if(databaseResult==-1 || alreadyConnected(req[1])) { //si le client n'est pas dans la base, on le kick qDebug() << "SERVER kicked " + req[1]; clients[idClient].sock->abort(); } else { clients[idClient].name=req[1]; sendToClient("port@"+QString::number(allocatedPort),clients[idClient].sock); clients[idClient].port=allocatedPort; clients[idClient].isTeacher=databaseResult; clients[idClient].isSending=true; allocatedPort++; sendToClient("isTeacher@"+QString::number(databaseResult),clients[idClient].sock); setPipeline(); } } else if (req[0].compare("chat")==0) { sendToAll(message); } }