Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/masterserver/src/libraries/network/Server.cc @ 7633

Last change on this file since 7633 was 7633, checked in by smerkli, 14 years ago

done for today.

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