Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 2258 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
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, (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>
44#include <cassert>
45
46
47#include "ConnectionManager.h"
48#include "ClientConnectionListener.h"
49#include "GamestateManager.h"
50#include "ClientInformation.h"
51#include "util/Sleep.h"
52#include "core/ConsoleCommand.h"
53#include "core/CoreIncludes.h"
54#include "core/Iterator.h"
55#include "packet/Chat.h"
56#include "packet/Packet.h"
57#include "packet/Welcome.h"
58#include "packet/DeleteObjects.h"
59#include <util/Convert.h>
60#include "ChatListener.h"
61
62namespace orxonox
63{
64  const unsigned int MAX_FAILURES = 20;
65  const unsigned int NETWORK_FREQUENCY = 25;
66  const float NETWORK_PERIOD = (float)1/NETWORK_FREQUENCY;
67
68  /**
69  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
70  *
71  */
72  Server::Server() {
73    timeSinceLastUpdate_=0;
74    connection = new ConnectionManager();
75    gamestates_ = new GamestateManager();
76  }
77
78  Server::Server(int port){
79    timeSinceLastUpdate_=0;
80    connection = new ConnectionManager(port);
81    gamestates_ = new GamestateManager();
82  }
83
84  /**
85  * Constructor
86  * @param port Port to listen on
87  * @param bindAddress Address to listen on
88  */
89  Server::Server(int port, const std::string& bindAddress) {
90    timeSinceLastUpdate_=0;
91    connection = new ConnectionManager(port, bindAddress);
92    gamestates_ = new GamestateManager();
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;
102    connection = new ConnectionManager(port, bindAddress);
103    gamestates_ = new GamestateManager();
104  }
105
106  /**
107  * @brief Destructor
108  */
109  Server::~Server(){
110    if(connection)
111      delete connection;
112    if(gamestates_)
113      delete gamestates_;
114  }
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
132  bool Server::processChat(const std::string& message, unsigned int playerID){
133    ClientInformation *temp = ClientInformation::getBegin();
134    packet::Chat *chat;
135    while(temp){
136      chat = new packet::Chat(message, playerID);
137      chat->setClientID(temp->getID());
138      if(!chat->send())
139        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
140      temp = temp->next();
141    }
142//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
143    return true;
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;
156    if(timeSinceLastUpdate_>=NETWORK_PERIOD){
157      timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
158      gamestates_->processGamestates();
159      updateGamestate();
160    }
161  }
162
163  bool Server::queuePacket(ENetPacket *packet, int clientID){
164    return connection->addPacket(packet, clientID);
165  }
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  }
174
175  /**
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  /**
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:
201        if(ClientInformation::findClient(&event->peer->address))
202          disconnectClient(event);
203        break;
204      case ENET_EVENT_TYPE_RECEIVE:
205        if(!processPacket(event->packet, event->peer))
206          COUT(3) << "processing incoming packet failed" << std::endl;
207        break;
208      default:
209        break;
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() {
220    gamestates_->update();
221    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
222    //std::cout << "updated gamestate, sending it" << std::endl;
223    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
224    sendGameState();
225    sendObjectDeletes();
226    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
227    //std::cout << "sent gamestate" << std::endl;
228  }
229
230  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
231    packet::Packet *p = packet::Packet::createPacket(packet, peer);
232    return p->process();
233  }
234
235  /**
236  * sends the gamestate
237  */
238  bool Server::sendGameState() {
239    COUT(5) << "Server: starting function sendGameState" << std::endl;
240    ClientInformation *temp = ClientInformation::getBegin();
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();
246        if(!temp)
247          break;
248        //think this works without continue
249        continue;
250      }
251      COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
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;
256      packet::Gamestate *gs = gamestates_->popGameState(cid);
257      if(gs==NULL){
258        COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
259        temp = temp->next();
260        continue;
261      }
262      //std::cout << "adding gamestate" << std::endl;
263      gs->setClientID(cid);
264      if ( !gs->send() ){
265        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
266        temp->addFailure();
267      }else
268        temp->resetFailures();
269      added=true;
270      temp=temp->next();
271      // gs gets automatically deleted by enet callback
272    }
273    return true;
274  }
275
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  }
299
300
301  bool Server::addClient(ENetEvent *event){
302    static unsigned int newid=1;
303
304    COUT(2) << "Server: adding client" << std::endl;
305    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
306    if(!temp){
307      COUT(2) << "Server: could not add client" << std::endl;
308      return false;
309    }
310    /*if(temp==ClientInformation::getBegin()) { //not good if you use anything else than insertBack
311      newid=1;
312    }
313    else
314      newid=temp->prev()->getID()+1;*/
315    temp->setID(newid);
316    temp->setPeer(event->peer);
317
318    // inform all the listeners
319    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
320    while(listener){
321      listener->clientConnected(newid);
322      listener++;
323    }
324
325    newid++;
326
327    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
328    return createClient(temp->getID());
329}
330
331  bool Server::createClient(int clientID){
332    ClientInformation *temp = ClientInformation::findClient(clientID);
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;
341    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
342    w->setClientID(temp->getID());
343    bool b = w->send();
344    assert(b);
345    packet::Gamestate *g = new packet::Gamestate();
346    g->setClientID(temp->getID());
347    b = g->collectData(0);
348    if(!b)
349      return false; //no data for the client
350    b = g->compressData();
351    assert(b);
352    b = g->send();
353    assert(b);
354    return true;
355  }
356
357  bool Server::disconnectClient(ENetEvent *event){
358    COUT(4) << "removing client from list" << std::endl;
359    //return removeClient(head_->findClient(&(peer->address))->getID());
360
361    //boost::recursive_mutex::scoped_lock lock(head_->mutex_);
362    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
363    if(!client)
364      return false;
365    gamestates_->removeClient(client);
366
367// inform all the listeners
368    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
369    while(listener){
370      listener->clientDisconnected(client->getID());
371      listener++;
372    }
373
374    return ClientInformation::removeClient(event->peer);
375  }
376
377  void Server::disconnectClient(int clientID){
378    ClientInformation *client = ClientInformation::findClient(clientID);
379    if(client)
380      disconnectClient(client);
381  }
382  void Server::disconnectClient( ClientInformation *client){
383    connection->disconnectClient(client);
384    gamestates_->removeClient(client);
385  }
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){
396    ClientInformation *temp = ClientInformation::getBegin();
397    packet::Chat *chat;
398    while(temp){
399      chat = new packet::Chat(message, clientID);
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    }
405//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
406    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
407      it->incomingChat(message, clientID);
408
409    return true;
410  }
411
412}
Note: See TracBrowser for help on using the repository browser.