Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/netp6/src/network/Server.cc @ 3272

Last change on this file since 3272 was 3240, checked in by scheusso, 16 years ago

a lot of cleanup
some bugfixes (Thread, ThreadPool)
the biggest part of the network (~80% cpu time) is now multithreaded (1 thread for each client)

  • Property svn:eol-style set to native
File size: 11.6 KB
RevLine 
[1502]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
[3084]23 *      Oliver Scheuss
[1502]24 *   Co-authors:
25 *      ...
26 *
27 */
28
29//
30// C++ Implementation: Server
31//
32// Description:
33//
34//
35// Author:  Oliver Scheuss, (C) 2007
36//
37// Copyright: See COPYING file that comes with this distribution
38//
39//
40
41#include "Server.h"
42
[2773]43#include <enet/enet.h>
[1755]44#include <cassert>
[3214]45#include <string>
[1502]46
[3214]47#include "util/Debug.h"
[2896]48#include "core/Clock.h"
[3214]49#include "core/ObjectList.h"
[3240]50#include "core/Executor.h"
51#include "core/ThreadPool.h"
[1735]52#include "packet/Chat.h"
[3214]53#include "packet/ClassID.h"
54#include "packet/DeleteObjects.h"
55#include "packet/FunctionIDs.h"
56#include "packet/Gamestate.h"
[1735]57#include "packet/Welcome.h"
[2087]58#include "ChatListener.h"
[3214]59#include "ClientInformation.h"
[3084]60#include "FunctionCallManager.h"
[3214]61#include "GamestateManager.h"
[1502]62
[2171]63namespace orxonox
[1502]64{
[2087]65  const unsigned int MAX_FAILURES = 20;
[1747]66
[1502]67  /**
68  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
69  *
70  */
71  Server::Server() {
[3240]72    this->timeSinceLastUpdate_=0;
73    this->threadPool_ = new ThreadPool();
[1502]74  }
[1747]75
[1502]76  Server::Server(int port){
[3214]77    this->setPort( port );
[3240]78    this->timeSinceLastUpdate_=0;
79    this->threadPool_ = new ThreadPool();
[1502]80  }
81
82  /**
83  * Constructor
84  * @param port Port to listen on
85  * @param bindAddress Address to listen on
86  */
[2087]87  Server::Server(int port, const std::string& bindAddress) {
[3214]88    this->setPort( port );
89    this->setBindAddress( bindAddress );
[3240]90    this->timeSinceLastUpdate_=0;
91    this->threadPool_ = new ThreadPool();
[1502]92  }
93
94  /**
[1907]95  * @brief Destructor
96  */
97  Server::~Server(){
[3240]98    delete this->threadPool_;
[1907]99  }
[1502]100
101  /**
102  * This function opens the server by creating the listener thread
103  */
104  void Server::open() {
[3214]105    COUT(4) << "opening server" << endl;
106    this->openListener();
[1502]107    return;
108  }
109
110  /**
111  * This function closes the server
112  */
113  void Server::close() {
[3214]114    COUT(4) << "closing server" << endl;
115    this->disconnectClients();
116    this->closeListener();
[1502]117    return;
118  }
119
[2087]120  bool Server::processChat(const std::string& message, unsigned int playerID){
[1735]121    ClientInformation *temp = ClientInformation::getBegin();
[1907]122    packet::Chat *chat;
[1735]123    while(temp){
[1907]124      chat = new packet::Chat(message, playerID);
[1735]125      chat->setClientID(temp->getID());
126      if(!chat->send())
127        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
[1907]128      temp = temp->next();
[1735]129    }
[2087]130//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
[1907]131    return true;
[1502]132  }
133
134
135  /**
136  * Run this function once every tick
137  * calls processQueue and updateGamestate
138  * @param time time since last tick
139  */
[2896]140  void Server::update(const Clock& time) {
[3240]141    // receive incoming packets
[3214]142    Connection::processQueue();
[3240]143    // process incoming gamestates
144    GamestateManager::processGamestates();
145   
146    // pass sendFunctionCalls to worker thread pool
147    ExecutorStatic* functioncalls = createExecutor( createFunctor(&FunctionCallManager::sendCalls) );
148    this->threadPool_->passFunction( functioncalls, true );
149   
150    this->threadPool_->synchronise();
151   
[1502]152    //this steers our network frequency
[2896]153    timeSinceLastUpdate_+=time.getDeltaTime();
[3214]154    if(timeSinceLastUpdate_>=NETWORK_PERIOD)
155    {
[2087]156      timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
[3240]157//       ExecutorMember<GamestateManager>* updategamestate = createExecutor( createFunctor(&GamestateManager::updateGamestate);
158//       updategamestate->setObject( static_cast<GamestateManager*>(this) );
159//       this->threadPool_->passFunction( updategamestate );
[1502]160      updateGamestate();
161    }
[3214]162    sendPackets(); // flush the enet queue
[1502]163  }
[1747]164
[1735]165  bool Server::queuePacket(ENetPacket *packet, int clientID){
[3214]166    return ServerConnection::addPacket(packet, clientID);
[1735]167  }
[2087]168 
169  /**
170   * @brief: returns ping time to client in milliseconds
171   */
172  unsigned int Server::getPing(unsigned int clientID){
173    assert(ClientInformation::findClient(clientID));
174    return ClientInformation::findClient(clientID)->getRTT();
175  }
[1502]176
177  /**
[2087]178   * @brief: return packet loss ratio to client (scales from 0 to 1)
179   */
180  double Server::getPacketLoss(unsigned int clientID){
181    assert(ClientInformation::findClient(clientID));
182    return ClientInformation::findClient(clientID)->getPacketLoss();
183  }
[1502]184
185  /**
186  * takes a new snapshot of the gamestate and sends it to the clients
187  */
188  void Server::updateGamestate() {
[3240]189    if( ClientInformation::getBegin()==NULL )
[2662]190      //no client connected
[3240]191      return;
192    GamestateManager::update();
[1534]193    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
[1502]194    //std::cout << "updated gamestate, sending it" << std::endl;
195    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
196    sendGameState();
[1907]197    sendObjectDeletes();
[1534]198    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
[1502]199    //std::cout << "sent gamestate" << std::endl;
200  }
201
[1735]202  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
203    packet::Packet *p = packet::Packet::createPacket(packet, peer);
204    return p->process();
205  }
[1747]206
[1502]207  /**
208  * sends the gamestate
209  */
210  bool Server::sendGameState() {
[3240]211//     COUT(5) << "Server: starting function sendGameState" << std::endl;
212//     ClientInformation *temp = ClientInformation::getBegin();
213//     bool added=false;
214//     while(temp != NULL){
215//       if( !(temp->getSynched()) ){
216//         COUT(5) << "Server: not sending gamestate" << std::endl;
217//         temp=temp->next();
218//         if(!temp)
219//           break;
220//         continue;
221//       }
222//       COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
223//       COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
224//       int cid = temp->getID(); //get client id
225//       packet::Gamestate *gs = GamestateManager::popGameState(cid);
226//       if(gs==NULL){
227//         COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
228//         temp = temp->next();
229//         continue;
230//       }
231//       //std::cout << "adding gamestate" << std::endl;
232//       gs->setClientID(cid);
233//       if ( !gs->send() ){
234//         COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
235//         temp->addFailure();
236//       }else
237//         temp->resetFailures();
238//       added=true;
239//       temp=temp->next();
240//       // gs gets automatically deleted by enet callback
241//     }
242    GamestateManager::sendGamestates();
[1502]243    return true;
244  }
[1747]245
[1907]246  bool Server::sendObjectDeletes(){
247    ClientInformation *temp = ClientInformation::getBegin();
[2662]248    if( temp == NULL )
249      //no client connected
250      return true;
[1907]251    packet::DeleteObjects *del = new packet::DeleteObjects();
252    if(!del->fetchIDs())
253      return true;  //everything ok (no deletes this tick)
254//     COUT(3) << "sending DeleteObjects" << std::endl;
255    while(temp != NULL){
256      if( !(temp->getSynched()) ){
257        COUT(5) << "Server: not sending gamestate" << std::endl;
258        temp=temp->next();
259        continue;
260      }
261      int cid = temp->getID(); //get client id
262      packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
263      assert(cd);
264      cd->setClientID(cid);
265      if ( !cd->send() )
266        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
267      temp=temp->next();
268      // gs gets automatically deleted by enet callback
269    }
[3198]270    delete del;
[1907]271    return true;
272  }
[1747]273
[1907]274
[3214]275  void Server::addClient(ENetEvent *event){
[2087]276    static unsigned int newid=1;
277
278    COUT(2) << "Server: adding client" << std::endl;
[1735]279    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
[1502]280    if(!temp){
281      COUT(2) << "Server: could not add client" << std::endl;
282    }
[2087]283    temp->setID(newid);
[1502]284    temp->setPeer(event->peer);
[2087]285
286    // inform all the listeners
[2171]287    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
[2087]288    while(listener){
289      listener->clientConnected(newid);
290      listener++;
291    }
292
[3214]293    ++newid;
[2087]294
[1502]295    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
[3214]296    createClient(temp->getID());
[2087]297}
[1747]298
[1502]299  bool Server::createClient(int clientID){
[1735]300    ClientInformation *temp = ClientInformation::findClient(clientID);
[1502]301    if(!temp){
302      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
303      return false;
304    }
[3084]305    COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl;
306   
307    // synchronise class ids
[3214]308    syncClassid(temp->getID());
[3084]309   
310    // now synchronise functionIDs
311    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
312    fIDs->setClientID(clientID);
313    bool b = fIDs->send();
314    assert(b);
315   
[1502]316    temp->setSynched(true);
[3084]317    COUT(4) << "sending welcome" << std::endl;
[1735]318    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
319    w->setClientID(temp->getID());
[3084]320    b = w->send();
[1907]321    assert(b);
[1751]322    packet::Gamestate *g = new packet::Gamestate();
323    g->setClientID(temp->getID());
[3102]324    b = g->collectData(0,0x1);
[2087]325    if(!b)
326      return false; //no data for the client
[1907]327    b = g->compressData();
328    assert(b);
329    b = g->send();
330    assert(b);
[1502]331    return true;
332  }
[3198]333 
[3214]334  void Server::disconnectClient( ClientInformation *client ){
335    ServerConnection::disconnectClient( client );
[3240]336    GamestateManager::removeClient(client);
[3198]337// inform all the listeners
338    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
339    while(listener){
340      listener->clientDisconnected(client->getID());
341      ++listener;
342    }
343    delete client; //remove client from list
[1502]344  }
[2087]345
346  bool Server::chat(const std::string& message){
347      return this->sendChat(message, Host::getPlayerID());
348  }
349
350  bool Server::broadcast(const std::string& message){
351      return this->sendChat(message, CLIENTID_UNKNOWN);
352  }
353
354  bool Server::sendChat(const std::string& message, unsigned int clientID){
[1907]355    ClientInformation *temp = ClientInformation::getBegin();
356    packet::Chat *chat;
357    while(temp){
[2087]358      chat = new packet::Chat(message, clientID);
[1907]359      chat->setClientID(temp->getID());
360      if(!chat->send())
361        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
362      temp = temp->next();
363    }
[2087]364//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
[2171]365    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
[2087]366      it->incomingChat(message, clientID);
367
[1907]368    return true;
369  }
[1747]370
[3214]371  void Server::syncClassid(unsigned int clientID) {
372    int failures=0;
373    packet::ClassID *classid = new packet::ClassID();
374    classid->setClientID(clientID);
375    while(!classid->send() && failures < 10){
376      failures++;
377    }
378    assert(failures<10);
379    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
380  }
381
[1502]382}
Note: See TracBrowser for help on using the repository browser.