Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentation/src/libraries/network/Server.cc @ 7750

Last change on this file since 7750 was 7750, checked in by smerkli, 13 years ago

documentation.

  • Property svn:eol-style set to native
File size: 13.1 KB
Line 
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:
23 *      Oliver Scheuss
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
43#define WIN32_LEAN_AND_MEAN
44#include <enet/enet.h>
45#include <cassert>
46#include <string>
47
48#include "util/Clock.h"
49#include "util/Debug.h"
50#include "core/ObjectList.h"
51#include "core/command/Executor.h"
52#include "packet/Chat.h"
53#include "packet/ClassID.h"
54#include "packet/DeleteObjects.h"
55#include "packet/FunctionIDs.h"
56#include "packet/Gamestate.h"
57#include "packet/Welcome.h"
58#include "ChatListener.h"
59#include "ClientInformation.h"
60#include "FunctionCallManager.h"
61#include "GamestateManager.h"
62#include "WANDiscovery.h"
63
64namespace orxonox
65{
66  const unsigned int MAX_FAILURES = 20;
67
68  /**
69  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
70  *
71  */
72  Server::Server()
73  {
74    this->timeSinceLastUpdate_=0;
75  }
76
77  Server::Server(int port)
78  {
79    this->setPort( port );
80    this->timeSinceLastUpdate_=0;
81  }
82
83  /**
84  * Constructor
85  * @param port Port to listen on
86  * @param bindAddress Address to listen on
87  */
88  Server::Server(int port, const std::string& bindAddress)
89  {
90    this->setPort( port );
91    this->setBindAddress( bindAddress );
92    this->timeSinceLastUpdate_=0;
93  }
94
95  /**
96  * @brief Destructor
97  */
98  Server::~Server()
99  {
100  }
101
102
103  /** helper that connects to the master server */
104  void Server::helper_ConnectToMasterserver()
105  {
106    /* initialize it and see if it worked */
107    if( msc.initialize() )
108    { COUT(1) << "Error: could not initialize master server communications!\n";
109      return;
110    }
111
112    /* connect and see if it worked */
113    if( msc.connect( WANDiscovery::getInstance().getMSAddress().c_str(), 
114      ORX_MSERVER_PORT ) )
115    { COUT(1) << "Error: could not connect to master server!\n";
116      return;
117    }
118
119    /* now send the master server some note we're here */
120    msc.sendRequest( MSPROTO_GAME_SERVER " " MSPROTO_REGISTER_SERVER );
121  }
122
123  /**
124  * This function opens the server by creating the listener thread
125  */
126  void Server::open()
127  {
128    Host::setActive(true);
129    COUT(4) << "opening server" << endl;
130    this->openListener();
131   
132    /* make discoverable on LAN */
133    LANDiscoverable::setActivity(true);
134
135    /* make discoverable on WAN */
136    helper_ConnectToMasterserver();
137
138    /* done */
139    return;
140  }
141
142  /**
143  * This function closes the server
144  */
145  void Server::close()
146  {
147    Host::setActive(false);
148    COUT(4) << "closing server" << endl;
149    this->disconnectClients();
150    this->closeListener();
151    LANDiscoverable::setActivity(false);
152    return;
153  }
154
155  bool Server::processChat(const std::string& message, unsigned int playerID)
156  {
157    ClientInformation *temp = ClientInformation::getBegin();
158    packet::Chat *chat;
159    while(temp){
160      chat = new packet::Chat(message, playerID);
161      chat->setClientID(temp->getID());
162      if(!chat->send())
163        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
164      temp = temp->next();
165    }
166//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
167    return true;
168  }
169
170
171  /* TODO */
172  int rephandler( char *addr, ENetEvent *ev )
173  { 
174    /* handle incoming data */
175    /* TODO this is to be implemented. */
176
177    /* done handling, return all ok code 0 */
178    return 0;
179  }
180
181  void Server::helper_HandleMasterServerRequests()
182  { 
183    /* poll the master server for replies and see whether something
184     * has to be done or changed.
185     */
186    this->msc.pollForReply( rephandler ); 
187  }
188
189  /**
190  * Run this function once every tick
191  * calls processQueue and updateGamestate
192  * @param time time since last tick
193  */
194  void Server::update(const Clock& time)
195  {
196    // receive incoming packets
197    Connection::processQueue();
198
199    // receive and process incoming discovery packets
200    LANDiscoverable::update();
201
202    // receive and process requests from master server
203    /* todo */
204    //helper_HandleMasterServerRequests();
205
206    if ( ClientInformation::hasClients() )
207    {
208      // process incoming gamestates
209      GamestateManager::processGamestates();
210
211      // send function calls to clients
212      FunctionCallManager::sendCalls();
213
214      //this steers our network frequency
215      timeSinceLastUpdate_+=time.getDeltaTime();
216      if(timeSinceLastUpdate_>=NETWORK_PERIOD)
217      {
218        timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
219        updateGamestate();
220      }
221      sendPackets(); // flush the enet queue
222    }
223  }
224
225  bool Server::queuePacket(ENetPacket *packet, int clientID)
226  {
227    return ServerConnection::addPacket(packet, clientID);
228  }
229
230  /**
231   * @brief: returns ping time to client in milliseconds
232   */
233  unsigned int Server::getRTT(unsigned int clientID)
234  {
235    assert(ClientInformation::findClient(clientID));
236    return ClientInformation::findClient(clientID)->getRTT();
237  }
238
239  void Server::printRTT()
240  {
241    for( ClientInformation* temp=ClientInformation::getBegin(); temp!=0; temp=temp->next() )
242      COUT(0) << "Round trip time to client with ID: " << temp->getID() << " is " << temp->getRTT() << " ms" << endl;
243  }
244
245  /**
246   * @brief: return packet loss ratio to client (scales from 0 to 1)
247   */
248  double Server::getPacketLoss(unsigned int clientID)
249  {
250    assert(ClientInformation::findClient(clientID));
251    return ClientInformation::findClient(clientID)->getPacketLoss();
252  }
253
254  /**
255  * takes a new snapshot of the gamestate and sends it to the clients
256  */
257  void Server::updateGamestate()
258  {
259    if( ClientInformation::getBegin()==NULL )
260      //no client connected
261      return;
262    GamestateManager::update();
263    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
264    //std::cout << "updated gamestate, sending it" << std::endl;
265    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
266    sendGameState();
267    sendObjectDeletes();
268    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
269    //std::cout << "sent gamestate" << std::endl;
270  }
271
272  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
273    packet::Packet *p = packet::Packet::createPacket(packet, peer);
274    return p->process();
275  }
276
277  /**
278  * sends the gamestate
279  */
280  bool Server::sendGameState()
281  {
282//     COUT(5) << "Server: starting function sendGameState" << std::endl;
283//     ClientInformation *temp = ClientInformation::getBegin();
284//     bool added=false;
285//     while(temp != NULL){
286//       if( !(temp->getSynched()) ){
287//         COUT(5) << "Server: not sending gamestate" << std::endl;
288//         temp=temp->next();
289//         if(!temp)
290//           break;
291//         continue;
292//       }
293//       COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
294//       COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
295//       int cid = temp->getID(); //get client id
296//       packet::Gamestate *gs = GamestateManager::popGameState(cid);
297//       if(gs==NULL){
298//         COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
299//         temp = temp->next();
300//         continue;
301//       }
302//       //std::cout << "adding gamestate" << std::endl;
303//       gs->setClientID(cid);
304//       if ( !gs->send() ){
305//         COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
306//         temp->addFailure();
307//       }else
308//         temp->resetFailures();
309//       added=true;
310//       temp=temp->next();
311//       // gs gets automatically deleted by enet callback
312//     }
313    GamestateManager::sendGamestates();
314    return true;
315  }
316
317  bool Server::sendObjectDeletes()
318  {
319    ClientInformation *temp = ClientInformation::getBegin();
320    if( temp == NULL )
321      //no client connected
322      return true;
323    packet::DeleteObjects *del = new packet::DeleteObjects();
324    if(!del->fetchIDs())
325    {
326      delete del;
327      return true;  //everything ok (no deletes this tick)
328    }
329//     COUT(3) << "sending DeleteObjects" << std::endl;
330    while(temp != NULL){
331      if( !(temp->getSynched()) )
332      {
333        COUT(5) << "Server: not sending gamestate" << std::endl;
334        temp=temp->next();
335        continue;
336      }
337      int cid = temp->getID(); //get client id
338      packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
339      assert(cd);
340      cd->setClientID(cid);
341      if ( !cd->send() )
342        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
343      temp=temp->next();
344      // gs gets automatically deleted by enet callback
345    }
346    delete del;
347    return true;
348  }
349
350
351  void Server::addPeer(ENetEvent *event)
352  {
353    static unsigned int newid=1;
354
355    COUT(2) << "Server: adding client" << std::endl;
356    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
357    if(!temp)
358    {
359      COUT(2) << "Server: could not add client" << std::endl;
360    }
361    temp->setID(newid);
362    temp->setPeer(event->peer);
363
364    // inform all the listeners
365    ClientConnectionListener::broadcastClientConnected(newid);
366
367    ++newid;
368
369    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
370    createClient(temp->getID());
371}
372
373  void Server::removePeer(ENetEvent *event)
374  {
375    COUT(4) << "removing client from list" << std::endl;
376    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
377    if(!client)
378      return;
379    else
380    {
381      //ServerConnection::disconnectClient( client );
382      //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
383      delete client;
384    }
385  }
386
387  bool Server::createClient(int clientID)
388  {
389    ClientInformation *temp = ClientInformation::findClient(clientID);
390    if(!temp)
391    {
392      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
393      return false;
394    }
395    COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl;
396
397    // synchronise class ids
398    syncClassid(temp->getID());
399
400    // now synchronise functionIDs
401    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
402    fIDs->setClientID(clientID);
403    bool b = fIDs->send();
404    assert(b);
405
406    temp->setSynched(true);
407    COUT(4) << "sending welcome" << std::endl;
408    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
409    w->setClientID(temp->getID());
410    b = w->send();
411    assert(b);
412    packet::Gamestate *g = new packet::Gamestate();
413    g->setClientID(temp->getID());
414    b = g->collectData(0,0x1);
415    if(!b)
416      return false; //no data for the client
417    b = g->compressData();
418    assert(b);
419    b = g->send();
420    assert(b);
421    return true;
422  }
423
424  void Server::disconnectClient( ClientInformation *client )
425  {
426    ServerConnection::disconnectClient( client );
427    GamestateManager::removeClient(client);
428    // inform all the listeners
429    // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now
430  }
431
432  bool Server::chat(const std::string& message)
433  {
434      return this->sendChat(message, Host::getPlayerID());
435  }
436
437  bool Server::broadcast(const std::string& message)
438  {
439      return this->sendChat(message, CLIENTID_UNKNOWN);
440  }
441
442  bool Server::sendChat(const std::string& message, unsigned int clientID)
443  {
444    ClientInformation *temp = ClientInformation::getBegin();
445    packet::Chat *chat;
446    while(temp)
447    {
448      chat = new packet::Chat(message, clientID);
449      chat->setClientID(temp->getID());
450      if(!chat->send())
451        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
452      temp = temp->next();
453    }
454//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
455    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
456      it->incomingChat(message, clientID);
457
458    return true;
459  }
460
461  void Server::syncClassid(unsigned int clientID)
462  {
463    int failures=0;
464    packet::ClassID *classid = new packet::ClassID();
465    classid->setClientID(clientID);
466    while(!classid->send() && failures < 10){
467      failures++;
468    }
469    assert(failures<10);
470    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
471  }
472
473}
Note: See TracBrowser for help on using the repository browser.