Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

disconnect implemented, getting ready for testing.

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