Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

started implementing server pings, but need a change to masterservercomm soon.

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