Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/doc/src/libraries/network/Server.cc @ 7497

Last change on this file since 7497 was 7284, checked in by landauf, 14 years ago

merged consolecommands3 branch back to trunk.

note: the console command interface has changed completely, but the documentation is not yet up to date. just copy an existing command and change it to your needs, it's pretty self-explanatory. also the include files related to console commands are now located in core/command/. in the game it should work exactly like before, except for some changes in the auto-completion.

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