Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/network/Server.cc @ 2188

Last change on this file since 2188 was 2171, checked in by landauf, 16 years ago

merged revisions 2111-2170 from objecthierarchy branch back to trunk.

  • Property svn:eol-style set to native
File size: 12.4 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:
23 *      Oliver Scheuss, (C) 2007
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#include <iostream>
[1755]44#include <cassert>
[1502]45
46
47#include "ConnectionManager.h"
[2087]48#include "ClientConnectionListener.h"
[1735]49#include "GamestateManager.h"
[1502]50#include "ClientInformation.h"
51#include "util/Sleep.h"
[1534]52#include "core/ConsoleCommand.h"
[1752]53#include "core/CoreIncludes.h"
[1747]54#include "core/Iterator.h"
[1735]55#include "packet/Chat.h"
56#include "packet/Packet.h"
57#include "packet/Welcome.h"
[1907]58#include "packet/DeleteObjects.h"
[1751]59#include <util/Convert.h>
[2087]60#include "ChatListener.h"
[1502]61
[2171]62namespace orxonox
[1502]63{
[2087]64  const unsigned int MAX_FAILURES = 20;
65  const unsigned int NETWORK_FREQUENCY = 25;
66  const float NETWORK_PERIOD = (float)1/NETWORK_FREQUENCY;
[1747]67
[1502]68  /**
69  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
70  *
71  */
72  Server::Server() {
73    timeSinceLastUpdate_=0;
[1735]74    connection = new ConnectionManager();
75    gamestates_ = new GamestateManager();
[1502]76  }
[1747]77
[1502]78  Server::Server(int port){
79    timeSinceLastUpdate_=0;
[1735]80    connection = new ConnectionManager(port);
81    gamestates_ = new GamestateManager();
[1502]82  }
83
84  /**
85  * Constructor
86  * @param port Port to listen on
87  * @param bindAddress Address to listen on
88  */
[2087]89  Server::Server(int port, const std::string& bindAddress) {
[1502]90    timeSinceLastUpdate_=0;
[1735]91    connection = new ConnectionManager(port, bindAddress);
92    gamestates_ = new GamestateManager();
[1502]93  }
94
95  /**
96  * Constructor
97  * @param port Port to listen on
98  * @param bindAddress Address to listen on
99  */
100  Server::Server(int port, const char *bindAddress) {
101    timeSinceLastUpdate_=0;
[1735]102    connection = new ConnectionManager(port, bindAddress);
103    gamestates_ = new GamestateManager();
[1502]104  }
[2087]105
[1907]106  /**
107  * @brief Destructor
108  */
109  Server::~Server(){
110    if(connection)
111      delete connection;
112    if(gamestates_)
113      delete gamestates_;
114  }
[1502]115
116  /**
117  * This function opens the server by creating the listener thread
118  */
119  void Server::open() {
120    connection->createListener();
121    return;
122  }
123
124  /**
125  * This function closes the server
126  */
127  void Server::close() {
128    connection->quitListener();
129    return;
130  }
131
[2087]132  bool Server::processChat(const std::string& message, unsigned int playerID){
[1735]133    ClientInformation *temp = ClientInformation::getBegin();
[1907]134    packet::Chat *chat;
[1735]135    while(temp){
[1907]136      chat = new packet::Chat(message, playerID);
[1735]137      chat->setClientID(temp->getID());
138      if(!chat->send())
139        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
[1907]140      temp = temp->next();
[1735]141    }
[2087]142//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
[1907]143    return true;
[1502]144  }
145
146
147  /**
148  * Run this function once every tick
149  * calls processQueue and updateGamestate
150  * @param time time since last tick
151  */
152  void Server::tick(float time) {
153    processQueue();
154    //this steers our network frequency
155    timeSinceLastUpdate_+=time;
[2087]156    if(timeSinceLastUpdate_>=NETWORK_PERIOD){
157      timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
[1735]158      gamestates_->processGamestates();
[1502]159      updateGamestate();
160    }
161  }
[1747]162
[1735]163  bool Server::queuePacket(ENetPacket *packet, int clientID){
164    return connection->addPacket(packet, clientID);
165  }
[2087]166 
167  /**
168   * @brief: returns ping time to client in milliseconds
169   */
170  unsigned int Server::getPing(unsigned int clientID){
171    assert(ClientInformation::findClient(clientID));
172    return ClientInformation::findClient(clientID)->getRTT();
173  }
[1502]174
175  /**
[2087]176   * @brief: return packet loss ratio to client (scales from 0 to 1)
177   */
178  double Server::getPacketLoss(unsigned int clientID){
179    assert(ClientInformation::findClient(clientID));
180    return ClientInformation::findClient(clientID)->getPacketLoss();
181  }
182 
183  /**
[1502]184  * processes all the packets waiting in the queue
185  */
186  void Server::processQueue() {
187    ENetEvent *event;
188    while(!connection->queueEmpty()){
189      //std::cout << "Client " << clientID << " sent: " << std::endl;
190      //clientID here is a reference to grab clientID from ClientInformation
191      event = connection->getEvent();
192      if(!event)
193        continue;
194      assert(event->type != ENET_EVENT_TYPE_NONE);
195      switch( event->type ) {
196      case ENET_EVENT_TYPE_CONNECT:
197        COUT(3) << "processing event_Type_connect" << std::endl;
198        addClient(event);
199        break;
200      case ENET_EVENT_TYPE_DISCONNECT:
[1735]201        if(ClientInformation::findClient(&event->peer->address))
[1502]202          disconnectClient(event);
203        break;
204      case ENET_EVENT_TYPE_RECEIVE:
[1735]205        if(!processPacket(event->packet, event->peer))
206          COUT(3) << "processing incoming packet failed" << std::endl;
[1502]207        break;
[1556]208      default:
209        break;
[1502]210      }
211      delete event;
212      //if statement to catch case that packetbuffer is empty
213    }
214  }
215
216  /**
217  * takes a new snapshot of the gamestate and sends it to the clients
218  */
219  void Server::updateGamestate() {
[1735]220    gamestates_->update();
[1534]221    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
[1502]222    //std::cout << "updated gamestate, sending it" << std::endl;
223    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
224    sendGameState();
[1907]225    sendObjectDeletes();
[1534]226    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
[1502]227    //std::cout << "sent gamestate" << std::endl;
228  }
229
[1735]230  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
231    packet::Packet *p = packet::Packet::createPacket(packet, peer);
232    return p->process();
233  }
[1747]234
[1502]235  /**
236  * sends the gamestate
237  */
238  bool Server::sendGameState() {
239    COUT(5) << "Server: starting function sendGameState" << std::endl;
[1735]240    ClientInformation *temp = ClientInformation::getBegin();
[1502]241    bool added=false;
242    while(temp != NULL){
243      if( !(temp->getSynched()) ){
244        COUT(5) << "Server: not sending gamestate" << std::endl;
245        temp=temp->next();
[1735]246        if(!temp)
247          break;
[1502]248        //think this works without continue
249        continue;
250      }
[1534]251      COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
[1502]252      COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
253      int gid = temp->getGamestateID(); //get gamestate id
254      int cid = temp->getID(); //get client id
255      COUT(5) << "Server: got acked (gamestate) ID from clientlist: " << gid << std::endl;
[1735]256      packet::Gamestate *gs = gamestates_->popGameState(cid);
[1502]257      if(gs==NULL){
258        COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
[2087]259        temp = temp->next();
[1502]260        continue;
261      }
262      //std::cout << "adding gamestate" << std::endl;
[1735]263      gs->setClientID(cid);
264      if ( !gs->send() ){
[1747]265        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
[1502]266        temp->addFailure();
267      }else
268        temp->resetFailures();
269      added=true;
270      temp=temp->next();
[1735]271      // gs gets automatically deleted by enet callback
[1502]272    }
273    return true;
274  }
[1747]275
[1907]276  bool Server::sendObjectDeletes(){
277    ClientInformation *temp = ClientInformation::getBegin();
278    packet::DeleteObjects *del = new packet::DeleteObjects();
279    if(!del->fetchIDs())
280      return true;  //everything ok (no deletes this tick)
281//     COUT(3) << "sending DeleteObjects" << std::endl;
282    while(temp != NULL){
283      if( !(temp->getSynched()) ){
284        COUT(5) << "Server: not sending gamestate" << std::endl;
285        temp=temp->next();
286        continue;
287      }
288      int cid = temp->getID(); //get client id
289      packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
290      assert(cd);
291      cd->setClientID(cid);
292      if ( !cd->send() )
293        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
294      temp=temp->next();
295      // gs gets automatically deleted by enet callback
296    }
297    return true;
298  }
[1747]299
[1907]300
[1502]301  bool Server::addClient(ENetEvent *event){
[2087]302    static unsigned int newid=1;
303
304    COUT(2) << "Server: adding client" << std::endl;
[1735]305    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
[1502]306    if(!temp){
307      COUT(2) << "Server: could not add client" << std::endl;
308      return false;
309    }
[2087]310    /*if(temp==ClientInformation::getBegin()) { //not good if you use anything else than insertBack
311      newid=1;
[1502]312    }
313    else
[2087]314      newid=temp->prev()->getID()+1;*/
315    temp->setID(newid);
[1502]316    temp->setPeer(event->peer);
[2087]317
318    // inform all the listeners
[2171]319    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
[2087]320    while(listener){
321      listener->clientConnected(newid);
322      listener++;
323    }
324
325    newid++;
326
[1502]327    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
328    return createClient(temp->getID());
[2087]329}
[1747]330
[1502]331  bool Server::createClient(int clientID){
[1735]332    ClientInformation *temp = ClientInformation::findClient(clientID);
[1502]333    if(!temp){
334      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
335      return false;
336    }
337    COUT(4) << "Con.Man: creating client id: " << temp->getID() << std::endl;
338    connection->syncClassid(temp->getID());
339    temp->setSynched(true);
340    COUT(3) << "sending welcome" << std::endl;
[1735]341    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
342    w->setClientID(temp->getID());
[1907]343    bool b = w->send();
344    assert(b);
[1751]345    packet::Gamestate *g = new packet::Gamestate();
346    g->setClientID(temp->getID());
[1907]347    b = g->collectData(0);
[2087]348    if(!b)
349      return false; //no data for the client
[1907]350    b = g->compressData();
351    assert(b);
352    b = g->send();
353    assert(b);
[1502]354    return true;
355  }
[1747]356
[1502]357  bool Server::disconnectClient(ENetEvent *event){
358    COUT(4) << "removing client from list" << std::endl;
359    //return removeClient(head_->findClient(&(peer->address))->getID());
[1747]360
[1502]361    //boost::recursive_mutex::scoped_lock lock(head_->mutex_);
[1735]362    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
[1502]363    if(!client)
364      return false;
[1751]365    gamestates_->removeClient(client);
[2087]366
367// inform all the listeners
[2171]368    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
[2087]369    while(listener){
370      listener->clientDisconnected(client->getID());
371      listener++;
[1502]372    }
[2087]373
374    return ClientInformation::removeClient(event->peer);
[1502]375  }
376
377  void Server::disconnectClient(int clientID){
[1735]378    ClientInformation *client = ClientInformation::findClient(clientID);
[1502]379    if(client)
380      disconnectClient(client);
381  }
382  void Server::disconnectClient( ClientInformation *client){
383    connection->disconnectClient(client);
[1735]384    gamestates_->removeClient(client);
[1502]385  }
[2087]386
387  bool Server::chat(const std::string& message){
388      return this->sendChat(message, Host::getPlayerID());
389  }
390
391  bool Server::broadcast(const std::string& message){
392      return this->sendChat(message, CLIENTID_UNKNOWN);
393  }
394
395  bool Server::sendChat(const std::string& message, unsigned int clientID){
[1907]396    ClientInformation *temp = ClientInformation::getBegin();
397    packet::Chat *chat;
398    while(temp){
[2087]399      chat = new packet::Chat(message, clientID);
[1907]400      chat->setClientID(temp->getID());
401      if(!chat->send())
402        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
403      temp = temp->next();
404    }
[2087]405//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
[2171]406    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
[2087]407      it->incomingChat(message, clientID);
408
[1907]409    return true;
410  }
[1747]411
[1502]412}
Note: See TracBrowser for help on using the repository browser.