Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7744 was 7740, checked in by smerkli, 14 years ago

fixed server startup

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