Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/archive/tutorialHS09/src/libraries/network/Server.cc @ 10428

Last change on this file since 10428 was 5749, checked in by rgrieder, 15 years ago

Sorted out header file finding issues and updated/added precompiled header files.
PCH is not activated per default for the pong projects (only 7 files).

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