Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

disconnect implemented, switching to only use the MSC object of wandiscovery.

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