Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Removed some things and fixed some bugs

  • Property svn:eol-style set to native
File size: 12.9 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  /* TODO */
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
176    /* done handling, return all ok code 0 */
177    return 0;
178  }
179
180  void Server::helper_HandleMasterServerRequests()
181  { 
182    this->msc.pollForReply( rephandler ); 
183  }
184
185  /**
186  * Run this function once every tick
187  * calls processQueue and updateGamestate
188  * @param time time since last tick
189  */
190  void Server::update(const Clock& time)
191  {
192    // receive incoming packets
193    Connection::processQueue();
194
195    // receive and process incoming discovery packets
196    LANDiscoverable::update();
197
198    // receive and process requests from master server
199    /* todo */
200    //helper_HandleMasterServerRequests();
201
202    if ( ClientInformation::hasClients() )
203    {
204      // process incoming gamestates
205      GamestateManager::processGamestates();
206
207      // send function calls to clients
208      FunctionCallManager::sendCalls();
209
210      //this steers our network frequency
211      timeSinceLastUpdate_+=time.getDeltaTime();
212      if(timeSinceLastUpdate_>=NETWORK_PERIOD)
213      {
214        timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
215        updateGamestate();
216      }
217      sendPackets(); // flush the enet queue
218    }
219  }
220
221  bool Server::queuePacket(ENetPacket *packet, int clientID)
222  {
223    return ServerConnection::addPacket(packet, clientID);
224  }
225
226  /**
227   * @brief: returns ping time to client in milliseconds
228   */
229  unsigned int Server::getRTT(unsigned int clientID)
230  {
231    assert(ClientInformation::findClient(clientID));
232    return ClientInformation::findClient(clientID)->getRTT();
233  }
234
235  void Server::printRTT()
236  {
237    for( ClientInformation* temp=ClientInformation::getBegin(); temp!=0; temp=temp->next() )
238      COUT(0) << "Round trip time to client with ID: " << temp->getID() << " is " << temp->getRTT() << " ms" << endl;
239  }
240
241  /**
242   * @brief: return packet loss ratio to client (scales from 0 to 1)
243   */
244  double Server::getPacketLoss(unsigned int clientID)
245  {
246    assert(ClientInformation::findClient(clientID));
247    return ClientInformation::findClient(clientID)->getPacketLoss();
248  }
249
250  /**
251  * takes a new snapshot of the gamestate and sends it to the clients
252  */
253  void Server::updateGamestate()
254  {
255    if( ClientInformation::getBegin()==NULL )
256      //no client connected
257      return;
258    GamestateManager::update();
259    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
260    //std::cout << "updated gamestate, sending it" << std::endl;
261    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
262    sendGameState();
263    sendObjectDeletes();
264    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
265    //std::cout << "sent gamestate" << std::endl;
266  }
267
268  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
269    packet::Packet *p = packet::Packet::createPacket(packet, peer);
270    return p->process();
271  }
272
273  /**
274  * sends the gamestate
275  */
276  bool Server::sendGameState()
277  {
278//     COUT(5) << "Server: starting function sendGameState" << std::endl;
279//     ClientInformation *temp = ClientInformation::getBegin();
280//     bool added=false;
281//     while(temp != NULL){
282//       if( !(temp->getSynched()) ){
283//         COUT(5) << "Server: not sending gamestate" << std::endl;
284//         temp=temp->next();
285//         if(!temp)
286//           break;
287//         continue;
288//       }
289//       COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
290//       COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
291//       int cid = temp->getID(); //get client id
292//       packet::Gamestate *gs = GamestateManager::popGameState(cid);
293//       if(gs==NULL){
294//         COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
295//         temp = temp->next();
296//         continue;
297//       }
298//       //std::cout << "adding gamestate" << std::endl;
299//       gs->setClientID(cid);
300//       if ( !gs->send() ){
301//         COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
302//         temp->addFailure();
303//       }else
304//         temp->resetFailures();
305//       added=true;
306//       temp=temp->next();
307//       // gs gets automatically deleted by enet callback
308//     }
309    GamestateManager::sendGamestates();
310    return true;
311  }
312
313  bool Server::sendObjectDeletes()
314  {
315    ClientInformation *temp = ClientInformation::getBegin();
316    if( temp == NULL )
317      //no client connected
318      return true;
319    packet::DeleteObjects *del = new packet::DeleteObjects();
320    if(!del->fetchIDs())
321    {
322      delete del;
323      return true;  //everything ok (no deletes this tick)
324    }
325//     COUT(3) << "sending DeleteObjects" << std::endl;
326    while(temp != NULL){
327      if( !(temp->getSynched()) )
328      {
329        COUT(5) << "Server: not sending gamestate" << std::endl;
330        temp=temp->next();
331        continue;
332      }
333      int cid = temp->getID(); //get client id
334      packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
335      assert(cd);
336      cd->setClientID(cid);
337      if ( !cd->send() )
338        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
339      temp=temp->next();
340      // gs gets automatically deleted by enet callback
341    }
342    delete del;
343    return true;
344  }
345
346
347  void Server::addPeer(ENetEvent *event)
348  {
349    static unsigned int newid=1;
350
351    COUT(2) << "Server: adding client" << std::endl;
352    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
353    if(!temp)
354    {
355      COUT(2) << "Server: could not add client" << std::endl;
356    }
357    temp->setID(newid);
358    temp->setPeer(event->peer);
359
360    // inform all the listeners
361    ClientConnectionListener::broadcastClientConnected(newid);
362
363    ++newid;
364
365    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
366    createClient(temp->getID());
367}
368
369  void Server::removePeer(ENetEvent *event)
370  {
371    COUT(4) << "removing client from list" << std::endl;
372    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
373    if(!client)
374      return;
375    else
376    {
377      //ServerConnection::disconnectClient( client );
378      //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
379      delete client;
380    }
381  }
382
383  bool Server::createClient(int clientID)
384  {
385    ClientInformation *temp = ClientInformation::findClient(clientID);
386    if(!temp)
387    {
388      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
389      return false;
390    }
391    COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl;
392
393    // synchronise class ids
394    syncClassid(temp->getID());
395
396    // now synchronise functionIDs
397    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
398    fIDs->setClientID(clientID);
399    bool b = fIDs->send();
400    assert(b);
401
402    temp->setSynched(true);
403    COUT(4) << "sending welcome" << std::endl;
404    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
405    w->setClientID(temp->getID());
406    b = w->send();
407    assert(b);
408    packet::Gamestate *g = new packet::Gamestate();
409    g->setClientID(temp->getID());
410    b = g->collectData(0,0x1);
411    if(!b)
412      return false; //no data for the client
413    b = g->compressData();
414    assert(b);
415    b = g->send();
416    assert(b);
417    return true;
418  }
419
420  void Server::disconnectClient( ClientInformation *client )
421  {
422    ServerConnection::disconnectClient( client );
423    GamestateManager::removeClient(client);
424    // inform all the listeners
425    // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now
426  }
427
428  bool Server::chat(const std::string& message)
429  {
430      return this->sendChat(message, Host::getPlayerID());
431  }
432
433  bool Server::broadcast(const std::string& message)
434  {
435      return this->sendChat(message, CLIENTID_UNKNOWN);
436  }
437
438  bool Server::sendChat(const std::string& message, unsigned int clientID)
439  {
440    ClientInformation *temp = ClientInformation::getBegin();
441    packet::Chat *chat;
442    while(temp)
443    {
444      chat = new packet::Chat(message, clientID);
445      chat->setClientID(temp->getID());
446      if(!chat->send())
447        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
448      temp = temp->next();
449    }
450//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
451    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
452      it->incomingChat(message, clientID);
453
454    return true;
455  }
456
457  void Server::syncClassid(unsigned int clientID)
458  {
459    int failures=0;
460    packet::ClassID *classid = new packet::ClassID();
461    classid->setClientID(clientID);
462    while(!classid->send() && failures < 10){
463      failures++;
464    }
465    assert(failures<10);
466    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
467  }
468
469}
Note: See TracBrowser for help on using the repository browser.