Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7762 was 7762, checked in by smerkli, 15 years ago

changes for testing

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