Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

merged netp4 back to trunk

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