Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/multiplayerFS15/src/libraries/network/Server.cc @ 10427

Last change on this file since 10427 was 10427, checked in by frovelli, 9 years ago

Implemented custom servernames

  • Property svn:eol-style set to native
File size: 13.0 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"
[8858]49#include "util/Output.h"
[7284]50#include "core/command/Executor.h"
[1735]51#include "packet/Chat.h"
[3214]52#include "packet/ClassID.h"
53#include "packet/DeleteObjects.h"
54#include "packet/FunctionIDs.h"
55#include "packet/Gamestate.h"
[1735]56#include "packet/Welcome.h"
[8327]57// #include "ClientInformation.h"
[3084]58#include "FunctionCallManager.h"
[3214]59#include "GamestateManager.h"
[1502]60
[2171]61namespace orxonox
[1502]62{
[2087]63  const unsigned int MAX_FAILURES = 20;
[1747]64
[1502]65  /**
66  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
67  *
68  */
[7163]69  Server::Server()
70  {
[3304]71    this->timeSinceLastUpdate_=0;
[1502]72  }
[1747]73
[7163]74  Server::Server(int port)
75  {
[3214]76    this->setPort( port );
[3304]77    this->timeSinceLastUpdate_=0;
[1502]78  }
[10427]79/*
80  Server::Server(int port, const std::string name)
81  {
82    this->setPort( port );
83    this->timeSinceLastUpdate_=0;
84    this->serverName_=name;
85  }*/
[1502]86  /**
87  * Constructor
88  * @param port Port to listen on
89  * @param bindAddress Address to listen on
90  */
[7163]91  Server::Server(int port, const std::string& bindAddress)
92  {
[3214]93    this->setPort( port );
94    this->setBindAddress( bindAddress );
[3304]95    this->timeSinceLastUpdate_=0;
[1502]96  }
97
98  /**
[1907]99  * @brief Destructor
100  */
[7163]101  Server::~Server()
102  {
[1907]103  }
[1502]104
105  /**
106  * This function opens the server by creating the listener thread
107  */
[7163]108  void Server::open()
109  {
110    Host::setActive(true);
[8858]111    orxout(verbose, context::network) << "opening server" << endl;
[3214]112    this->openListener();
[8858]113
[7801]114    /* make discoverable on LAN */
[7163]115    LANDiscoverable::setActivity(true);
[7801]116
117    /* make discoverable on WAN */
118    WANDiscoverable::setActivity(true);
119
120    /* done */
[1502]121    return;
122  }
123
124  /**
125  * This function closes the server
126  */
[7163]127  void Server::close()
128  {
129    Host::setActive(false);
[8858]130    orxout(verbose, context::network) << "closing server" << endl;
[3214]131    this->disconnectClients();
132    this->closeListener();
[7801]133
134    /* tell master server we're closing */
[8858]135    orxout(internal_info, context::network) << "disconnecting." << endl;
136    WANDiscoverable::setActivity(false);
137    orxout(internal_info, context::network) << "disconnecting done" << endl;
[7801]138
[7163]139    LANDiscoverable::setActivity(false);
[1502]140    return;
141  }
142
143  /**
144  * Run this function once every tick
145  * calls processQueue and updateGamestate
146  * @param time time since last tick
147  */
[7163]148  void Server::update(const Clock& time)
149  {
[3304]150    // receive incoming packets
[3214]151    Connection::processQueue();
[7801]152
[7163]153    // receive and process incoming discovery packets
154    LANDiscoverable::update();
[6417]155
[8327]156    if ( GamestateManager::hasPeers() )
[3214]157    {
[3304]158      // process incoming gamestates
159      GamestateManager::processGamestates();
[7801]160      FunctionCallManager::processBufferedFunctionCalls();
[6417]161
[3304]162      // send function calls to clients
[7801]163      FunctionCallManager::sendCalls( static_cast<Host*>(this) );
[6417]164
[3304]165      //this steers our network frequency
166      timeSinceLastUpdate_+=time.getDeltaTime();
167      if(timeSinceLastUpdate_>=NETWORK_PERIOD)
168      {
169        timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
170        updateGamestate();
171      }
[7801]172//       sendPackets(); // flush the enet queue
[1502]173    }
174  }
[1747]175
[7801]176  void Server::queuePacket(ENetPacket *packet, int clientID, uint8_t channelID)
[7163]177  {
[7801]178    ServerConnection::addPacket(packet, clientID, channelID);
[1735]179  }
[6417]180
[2087]181  /**
[6417]182   * @brief: returns ping time to client in milliseconds
[2087]183   */
[7163]184  unsigned int Server::getRTT(unsigned int clientID)
185  {
[8327]186//     assert(ClientInformation::findClient(clientID));
187//     return ClientInformation::findClient(clientID)->getRTT();
188    // TODO: reimplement
189    return 0;
[2087]190  }
[6417]191
[5961]192  void Server::printRTT()
193  {
[8327]194//     for( ClientInformation* temp=ClientInformation::getBegin(); temp!=0; temp=temp->next() )
[8858]195//       orxout(message) << "Round trip time to client with ID: " << temp->getID() << " is " << temp->getRTT() << " ms" << endl;
[5961]196  }
[1502]197
198  /**
[2087]199   * @brief: return packet loss ratio to client (scales from 0 to 1)
200   */
[8351]201  float Server::getPacketLoss(unsigned int clientID)
[7163]202  {
[8327]203//     assert(ClientInformation::findClient(clientID));
204//     return ClientInformation::findClient(clientID)->getPacketLoss();
205    return 0.;
[2087]206  }
[1502]207
208  /**
209  * takes a new snapshot of the gamestate and sends it to the clients
210  */
[7163]211  void Server::updateGamestate()
212  {
[8327]213    if( this->clientIDs_.size()==0 )
[2662]214      //no client connected
[3304]215      return;
216    GamestateManager::update();
[8858]217//     orxout(verbose_more, context::network) << "Server: one gamestate update complete, goig to sendGameState" << endl;
218    //orxout(verbose_more, context::network) << "updated gamestate, sending it" << endl;
[1502]219    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
[7801]220    sendGameStates();
[1907]221    sendObjectDeletes();
[8858]222//     orxout(verbose_more, context::network) << "Server: one sendGameState turn complete, repeat in next tick" << endl;
223    //orxout(verbose_more, context::network) << "sent gamestate" << endl;
[1502]224  }
225
226  /**
[7801]227  * sends the current gamestate to all peers
[1502]228  */
[7801]229  bool Server::sendGameStates()
[7163]230  {
[7801]231    std::vector<packet::Gamestate*> gamestates = GamestateManager::getGamestates();
232    std::vector<packet::Gamestate*>::iterator it;
233    for( it = gamestates.begin(); it != gamestates.end(); ++it )
234    {
235      (*it)->send(static_cast<Host*>(this));
236    }
[1502]237    return true;
238  }
[1747]239
[7801]240
[7163]241  bool Server::sendObjectDeletes()
242  {
[8327]243//     ClientInformation *temp = ClientInformation::getBegin();
244//     if( temp == NULL )
[2662]245      //no client connected
[8327]246    if( this->clientIDs_.size()==0 )
[2662]247      return true;
[1907]248    packet::DeleteObjects *del = new packet::DeleteObjects();
249    if(!del->fetchIDs())
[5929]250    {
251      delete del;
[1907]252      return true;  //everything ok (no deletes this tick)
[5929]253    }
[8858]254//     orxout(verbose, context::network) << "sending DeleteObjects" << endl;
[8327]255//     while(temp != NULL){
256//       if( !(temp->getSynched()) )
257//       {
[8858]258//         orxout(verbose_more, context::network) << "Server: not sending gamestate" << endl;
[8327]259//         temp=temp->next();
260//         continue;
261//       }
262//       int cid = temp->getID(); //get client id
263//       packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
264//       assert(cd);
265    del->setPeerID(NETWORK_PEER_ID_BROADCAST);
266    if ( !del->send( static_cast<Host*>(this) ) )
[8858]267      orxout(internal_warning, context::network) << "Server: could not broadcast deleteObjects packet" << endl;
[8327]268//       temp=temp->next();
[1907]269      // gs gets automatically deleted by enet callback
[8327]270//     }
271//     delete del;
[1907]272    return true;
273  }
[1747]274
[1907]275
[8327]276  void Server::addPeer(uint32_t peerID)
[7163]277  {
[8327]278//     static unsigned int newid=1;
[8858]279//
280//     orxout(internal_info, context::network) << "Server: adding client" << endl;
[8327]281//     ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
282//     if(!temp)
283//     {
[8858]284//       orxout(internal_warning, context::network) << "Server: could not add client" << endl;
[8327]285//     }
286//     temp->setID(newid);
287//     temp->setPeer(event->peer);
[2087]288
289    // inform all the listeners
[8327]290    this->clientIDs_.push_back(peerID);
291    ClientConnectionListener::broadcastClientConnected(peerID);
292    GamestateManager::addPeer(peerID);
[2087]293
[8327]294//     ++newid;
[2087]295
[8858]296    orxout(internal_info, context::network) << "Server: added client id: " << peerID << endl;
[8327]297    createClient(peerID);
[2087]298}
[1747]299
[8327]300  void Server::removePeer(uint32_t peerID)
[5929]301  {
[8858]302    orxout(verbose, context::network) << "removing client from list" << endl;
[8327]303//     ClientInformation *client = ClientInformation::findClient(&event->peer->address);
304//     if(!client)
305//       return;
306//     else
307//     {
308  std::vector<uint32_t>::iterator it;
309  for( it=this->clientIDs_.begin(); it!=this->clientIDs_.end(); ++it )
310  {
311    if( *it == peerID )
[5929]312    {
[8327]313      this->clientIDs_.erase(it);
314      break;
315    }
316  }
317  ClientConnectionListener::broadcastClientDisconnected(peerID);
318  GamestateManager::removePeer(peerID);
[5929]319      //ServerConnection::disconnectClient( client );
[5961]320      //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
[8327]321//       delete client;
322//     }
[5929]323  }
[8858]324
[7801]325  void Server::processPacket(packet::Packet* packet)
326  {
327    if( packet->isReliable() )
328    {
[8327]329      if( this->getLastReceivedGamestateID(packet->getPeerID()) >= packet->getRequiredGamestateID() )
[7801]330        packet->process(static_cast<Host*>(this));
331      else
332        this->packetQueue_.push_back(packet);
333    }
334    else
335      packet->process(static_cast<Host*>(this));
336  }
[5929]337
[7801]338
[7163]339  bool Server::createClient(int clientID)
340  {
[8327]341//     ClientInformation *temp = ClientInformation::findClient(clientID);
342//     if(!temp)
343//     {
[8858]344//       orxout(internal_error, context::network) << "Server. could not create client with id: " << clientID << endl;
[8327]345//       return false;
346//     }
[8858]347//     orxout(verbose, context::network) << "Con.Man: creating client id: " << temp->getID() << endl;
[6417]348
[3084]349    // synchronise class ids
[8327]350    syncClassid(clientID);
[6417]351
[3084]352    // now synchronise functionIDs
353    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
[7801]354    fIDs->setPeerID(clientID);
355    bool b = fIDs->send( static_cast<Host*>(this) );
[3084]356    assert(b);
[6417]357
[8327]358//     temp->setSynched(true);
[7801]359    GamestateManager::setSynched(clientID);
[8858]360
361    orxout(verbose, context::network) << "sending welcome" << endl;
[8706]362    packet::Welcome *w = new packet::Welcome(clientID);
[8327]363    w->setPeerID(clientID);
[7801]364    b = w->send( static_cast<Host*>(this) );
[1907]365    assert(b);
[8327]366//     packet::Gamestate *g = new packet::Gamestate();
367//     g->setPeerID(clientID);
368//     b = g->collectData(0,packet::GAMESTATE_MODE_SERVER);
[7801]369//     assert(b);
[8327]370//     if(!b)
371//       return false; //no data for the client
372// //     b = g->compressData();
373// //     assert(b);
374//     b = g->send( static_cast<Host*>(this) );
375//     assert(b);
[1502]376    return true;
377  }
[6417]378
[8327]379  void Server::disconnectClient( uint32_t clientID )
[7163]380  {
[8327]381    ServerConnection::disconnectClient( clientID );
382    GamestateManager::removePeer( clientID );
[5929]383    // inform all the listeners
[5961]384    // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now
[1502]385  }
[2087]386
[8858]387  /**
388   * @brief Sends a chat message to the given target ID.
389   * @param message message to be sent
390   * @param sourceID the ID of the sender
391   * @param targetID the ID of the receiver
392   */
393  void Server::doSendChat(const std::string& message, unsigned int sourceID, unsigned int targetID)
[7163]394  {
[8858]395    // check if the target exists. just ignore the message otherwise
396    if (!this->isValidTarget(targetID)) // TODO: remove this if an invalid clientIDs don't trigger assertions anymore
397      return;
398
399    // send the message to the target
400    packet::Chat* packet = new packet::Chat(message, sourceID, targetID);
401    packet->setPeerID(targetID);
402    packet->send( static_cast<Host*>(this) );
403
404    // if the target is (or includes) this host as well, call the parent function which passes the message to the listeners
405    if (targetID == NETWORK_PEER_ID_BROADCAST || targetID == Host::getPlayerID())
406      Host::doReceiveChat(message, sourceID, targetID);
[2087]407  }
408
[8858]409  /**
410   * @brief Gets called if a packet::Chat packet is received. Forwards the packet to the target
411   * and calls the parent function if necessary.
412   */
413  void Server::doReceiveChat(const std::string& message, unsigned int sourceID, unsigned int targetID)
[7163]414  {
[8858]415      this->doSendChat(message, sourceID, targetID);
[2087]416  }
417
[8858]418  /**
419   * @brief Returns true if the target ID is in the list of clients (or if it
420   * corresponds to the broadcast or the server ID).
421   */
422  bool Server::isValidTarget(unsigned int targetID)
[7163]423  {
[8858]424    if (targetID == NETWORK_PEER_ID_BROADCAST || targetID == NETWORK_PEER_ID_SERVER)
425      return true;
[2087]426
[8858]427    std::vector<uint32_t>::iterator it;
428    for( it=this->clientIDs_.begin(); it!=this->clientIDs_.end(); ++it )
429      if( *it == targetID )
430        return true;
431
432    return false;
[1907]433  }
[1747]434
[7163]435  void Server::syncClassid(unsigned int clientID)
436  {
[3214]437    int failures=0;
438    packet::ClassID *classid = new packet::ClassID();
[7801]439    classid->setPeerID(clientID);
440    while(!classid->send( static_cast<Host*>(this) ) && failures < 10){
[3214]441      failures++;
442    }
443    assert(failures<10);
[8858]444    orxout(verbose, context::network) << "syncClassid:\tall synchClassID packets have been sent" << endl;
[3214]445  }
446
[1502]447}
Note: See TracBrowser for help on using the repository browser.