Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentation/src/libraries/network/Server.cc @ 7768

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

disconnect works now.

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