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, 15 years ago

fixed server startup

  • Property svn:eol-style set to native
File size: 12.9 KB
RevLine 
[1502]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:
[3084]23 *      Oliver Scheuss
[1502]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
[5749]43#define WIN32_LEAN_AND_MEAN
[2773]44#include <enet/enet.h>
[1755]45#include <cassert>
[3214]46#include <string>
[1502]47
[5929]48#include "util/Clock.h"
[3214]49#include "util/Debug.h"
50#include "core/ObjectList.h"
[7284]51#include "core/command/Executor.h"
[1735]52#include "packet/Chat.h"
[3214]53#include "packet/ClassID.h"
54#include "packet/DeleteObjects.h"
55#include "packet/FunctionIDs.h"
56#include "packet/Gamestate.h"
[1735]57#include "packet/Welcome.h"
[2087]58#include "ChatListener.h"
[3214]59#include "ClientInformation.h"
[3084]60#include "FunctionCallManager.h"
[3214]61#include "GamestateManager.h"
[1502]62
[2171]63namespace orxonox
[1502]64{
[2087]65  const unsigned int MAX_FAILURES = 20;
[1747]66
[1502]67  /**
68  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
69  *
70  */
[7163]71  Server::Server()
72  {
[3304]73    this->timeSinceLastUpdate_=0;
[1502]74  }
[1747]75
[7163]76  Server::Server(int port)
77  {
[3214]78    this->setPort( port );
[3304]79    this->timeSinceLastUpdate_=0;
[1502]80  }
81
82  /**
83  * Constructor
84  * @param port Port to listen on
85  * @param bindAddress Address to listen on
86  */
[7163]87  Server::Server(int port, const std::string& bindAddress)
88  {
[3214]89    this->setPort( port );
90    this->setBindAddress( bindAddress );
[3304]91    this->timeSinceLastUpdate_=0;
[1502]92  }
93
94  /**
[1907]95  * @brief Destructor
96  */
[7163]97  Server::~Server()
98  {
[1907]99  }
[1502]100
[7739]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 */
[7740]112    if( msc.connect( MS_ADDRESS, ORX_MSERVER_PORT ) )
[7739]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
[1502]121  /**
122  * This function opens the server by creating the listener thread
123  */
[7163]124  void Server::open()
125  {
126    Host::setActive(true);
[3214]127    COUT(4) << "opening server" << endl;
128    this->openListener();
[7739]129   
130    /* make discoverable on LAN */
[7163]131    LANDiscoverable::setActivity(true);
[7739]132
133    /* make discoverable on WAN */
134    helper_ConnectToMasterserver();
135
136    /* done */
[1502]137    return;
138  }
139
140  /**
141  * This function closes the server
142  */
[7163]143  void Server::close()
144  {
145    Host::setActive(false);
[3214]146    COUT(4) << "closing server" << endl;
147    this->disconnectClients();
148    this->closeListener();
[7163]149    LANDiscoverable::setActivity(false);
[1502]150    return;
151  }
152
[7163]153  bool Server::processChat(const std::string& message, unsigned int playerID)
154  {
[1735]155    ClientInformation *temp = ClientInformation::getBegin();
[1907]156    packet::Chat *chat;
[1735]157    while(temp){
[1907]158      chat = new packet::Chat(message, playerID);
[1735]159      chat->setClientID(temp->getID());
160      if(!chat->send())
161        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
[1907]162      temp = temp->next();
[1735]163    }
[2087]164//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
[1907]165    return true;
[1502]166  }
167
168
[7739]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
[1502]183  /**
184  * Run this function once every tick
185  * calls processQueue and updateGamestate
186  * @param time time since last tick
187  */
[7163]188  void Server::update(const Clock& time)
189  {
[3304]190    // receive incoming packets
[3214]191    Connection::processQueue();
[7739]192
[7163]193    // receive and process incoming discovery packets
194    LANDiscoverable::update();
[6417]195
[7739]196    // receive and process requests from master server
[7740]197    /* todo */
198    //helper_HandleMasterServerRequests();
[7739]199
[3304]200    if ( ClientInformation::hasClients() )
[3214]201    {
[3304]202      // process incoming gamestates
203      GamestateManager::processGamestates();
[6417]204
[3304]205      // send function calls to clients
[3084]206      FunctionCallManager::sendCalls();
[6417]207
[3304]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
[1502]216    }
217  }
[1747]218
[7163]219  bool Server::queuePacket(ENetPacket *packet, int clientID)
220  {
[3214]221    return ServerConnection::addPacket(packet, clientID);
[1735]222  }
[6417]223
[2087]224  /**
[6417]225   * @brief: returns ping time to client in milliseconds
[2087]226   */
[7163]227  unsigned int Server::getRTT(unsigned int clientID)
228  {
[2087]229    assert(ClientInformation::findClient(clientID));
230    return ClientInformation::findClient(clientID)->getRTT();
231  }
[6417]232
[5961]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  }
[1502]238
239  /**
[2087]240   * @brief: return packet loss ratio to client (scales from 0 to 1)
241   */
[7163]242  double Server::getPacketLoss(unsigned int clientID)
243  {
[2087]244    assert(ClientInformation::findClient(clientID));
245    return ClientInformation::findClient(clientID)->getPacketLoss();
246  }
[1502]247
248  /**
249  * takes a new snapshot of the gamestate and sends it to the clients
250  */
[7163]251  void Server::updateGamestate()
252  {
[3304]253    if( ClientInformation::getBegin()==NULL )
[2662]254      //no client connected
[3304]255      return;
256    GamestateManager::update();
[1534]257    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
[1502]258    //std::cout << "updated gamestate, sending it" << std::endl;
259    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
260    sendGameState();
[1907]261    sendObjectDeletes();
[1534]262    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
[1502]263    //std::cout << "sent gamestate" << std::endl;
264  }
265
[1735]266  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
267    packet::Packet *p = packet::Packet::createPacket(packet, peer);
268    return p->process();
269  }
[1747]270
[1502]271  /**
272  * sends the gamestate
273  */
[7163]274  bool Server::sendGameState()
275  {
[3304]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();
[1502]308    return true;
309  }
[1747]310
[7163]311  bool Server::sendObjectDeletes()
312  {
[1907]313    ClientInformation *temp = ClientInformation::getBegin();
[2662]314    if( temp == NULL )
315      //no client connected
316      return true;
[1907]317    packet::DeleteObjects *del = new packet::DeleteObjects();
318    if(!del->fetchIDs())
[5929]319    {
320      delete del;
[1907]321      return true;  //everything ok (no deletes this tick)
[5929]322    }
[1907]323//     COUT(3) << "sending DeleteObjects" << std::endl;
324    while(temp != NULL){
[7163]325      if( !(temp->getSynched()) )
326      {
[1907]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    }
[3198]340    delete del;
[1907]341    return true;
342  }
[1747]343
[1907]344
[7163]345  void Server::addPeer(ENetEvent *event)
346  {
[2087]347    static unsigned int newid=1;
348
349    COUT(2) << "Server: adding client" << std::endl;
[1735]350    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
[7163]351    if(!temp)
352    {
[1502]353      COUT(2) << "Server: could not add client" << std::endl;
354    }
[2087]355    temp->setID(newid);
[1502]356    temp->setPeer(event->peer);
[2087]357
358    // inform all the listeners
[5929]359    ClientConnectionListener::broadcastClientConnected(newid);
[2087]360
[3214]361    ++newid;
[2087]362
[1502]363    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
[3214]364    createClient(temp->getID());
[2087]365}
[1747]366
[5929]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 );
[5961]376      //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
[5929]377      delete client;
378    }
379  }
380
[7163]381  bool Server::createClient(int clientID)
382  {
[1735]383    ClientInformation *temp = ClientInformation::findClient(clientID);
[7163]384    if(!temp)
385    {
[1502]386      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
387      return false;
388    }
[3084]389    COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl;
[6417]390
[3084]391    // synchronise class ids
[3214]392    syncClassid(temp->getID());
[6417]393
[3084]394    // now synchronise functionIDs
395    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
396    fIDs->setClientID(clientID);
397    bool b = fIDs->send();
398    assert(b);
[6417]399
[1502]400    temp->setSynched(true);
[3084]401    COUT(4) << "sending welcome" << std::endl;
[1735]402    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
403    w->setClientID(temp->getID());
[3084]404    b = w->send();
[1907]405    assert(b);
[1751]406    packet::Gamestate *g = new packet::Gamestate();
407    g->setClientID(temp->getID());
[3102]408    b = g->collectData(0,0x1);
[2087]409    if(!b)
410      return false; //no data for the client
[1907]411    b = g->compressData();
412    assert(b);
413    b = g->send();
414    assert(b);
[1502]415    return true;
416  }
[6417]417
[7163]418  void Server::disconnectClient( ClientInformation *client )
419  {
[3214]420    ServerConnection::disconnectClient( client );
[3304]421    GamestateManager::removeClient(client);
[5929]422    // inform all the listeners
[5961]423    // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now
[1502]424  }
[2087]425
[7163]426  bool Server::chat(const std::string& message)
427  {
[2087]428      return this->sendChat(message, Host::getPlayerID());
429  }
430
[7163]431  bool Server::broadcast(const std::string& message)
432  {
[2087]433      return this->sendChat(message, CLIENTID_UNKNOWN);
434  }
435
[7163]436  bool Server::sendChat(const std::string& message, unsigned int clientID)
437  {
[1907]438    ClientInformation *temp = ClientInformation::getBegin();
439    packet::Chat *chat;
[7163]440    while(temp)
441    {
[2087]442      chat = new packet::Chat(message, clientID);
[1907]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    }
[2087]448//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
[2171]449    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
[2087]450      it->incomingChat(message, clientID);
451
[1907]452    return true;
453  }
[1747]454
[7163]455  void Server::syncClassid(unsigned int clientID)
456  {
[3214]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
[1502]467}
Note: See TracBrowser for help on using the repository browser.