Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/netp4/src/network/Server.cc @ 3137

Last change on this file since 3137 was 3137, checked in by scheusso, 15 years ago

various performance and memory issues fixed

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