Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

disconnect works now.

  • Property svn:eol-style set to native
File size: 13.3 KB
RevLine 
[1502]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:
[3084]23 *      Oliver Scheuss
[1502]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
[5749]43#define WIN32_LEAN_AND_MEAN
[2773]44#include <enet/enet.h>
[1755]45#include <cassert>
[3214]46#include <string>
[1502]47
[5929]48#include "util/Clock.h"
[3214]49#include "util/Debug.h"
50#include "core/ObjectList.h"
[7284]51#include "core/command/Executor.h"
[1735]52#include "packet/Chat.h"
[3214]53#include "packet/ClassID.h"
54#include "packet/DeleteObjects.h"
55#include "packet/FunctionIDs.h"
56#include "packet/Gamestate.h"
[1735]57#include "packet/Welcome.h"
[2087]58#include "ChatListener.h"
[3214]59#include "ClientInformation.h"
[3084]60#include "FunctionCallManager.h"
[3214]61#include "GamestateManager.h"
[7745]62#include "WANDiscovery.h"
[1502]63
[2171]64namespace orxonox
[1502]65{
[2087]66  const unsigned int MAX_FAILURES = 20;
[1747]67
[1502]68  /**
69  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
70  *
71  */
[7163]72  Server::Server()
73  {
[3304]74    this->timeSinceLastUpdate_=0;
[1502]75  }
[1747]76
[7163]77  Server::Server(int port)
78  {
[3214]79    this->setPort( port );
[3304]80    this->timeSinceLastUpdate_=0;
[1502]81  }
82
83  /**
84  * Constructor
85  * @param port Port to listen on
86  * @param bindAddress Address to listen on
87  */
[7163]88  Server::Server(int port, const std::string& bindAddress)
89  {
[3214]90    this->setPort( port );
91    this->setBindAddress( bindAddress );
[3304]92    this->timeSinceLastUpdate_=0;
[1502]93  }
94
95  /**
[1907]96  * @brief Destructor
97  */
[7163]98  Server::~Server()
99  {
[1907]100  }
[1502]101
[7739]102
[7750]103  /** helper that connects to the master server */
[7739]104  void Server::helper_ConnectToMasterserver()
105  {
[7763]106    WANDiscovery::getInstance().msc.sendRequest( MSPROTO_GAME_SERVER " " 
107      MSPROTO_REGISTER_SERVER );
[7739]108  }
109
[1502]110  /**
111  * This function opens the server by creating the listener thread
112  */
[7163]113  void Server::open()
114  {
115    Host::setActive(true);
[3214]116    COUT(4) << "opening server" << endl;
117    this->openListener();
[7739]118   
119    /* make discoverable on LAN */
[7163]120    LANDiscoverable::setActivity(true);
[7739]121
122    /* make discoverable on WAN */
[7756]123    /* TODO this needs to be optional, we need a switch from the UI to
124     * enable/disable this
125     */
[7739]126    helper_ConnectToMasterserver();
127
128    /* done */
[1502]129    return;
130  }
131
132  /**
133  * This function closes the server
134  */
[7163]135  void Server::close()
136  {
137    Host::setActive(false);
[3214]138    COUT(4) << "closing server" << endl;
139    this->disconnectClients();
140    this->closeListener();
[7763]141
142    /* tell master server we're closing */
[7762]143    COUT(2) << "disconnecting." << endl;
[7763]144    WANDiscovery::getInstance().msc.sendRequest( MSPROTO_GAME_SERVER " " 
145      MSPROTO_SERVERDC );
[7762]146    COUT(2) << "disconnecting done" << endl;
[7763]147
[7163]148    LANDiscoverable::setActivity(false);
[1502]149    return;
150  }
151
[7163]152  bool Server::processChat(const std::string& message, unsigned int playerID)
153  {
[1735]154    ClientInformation *temp = ClientInformation::getBegin();
[1907]155    packet::Chat *chat;
[1735]156    while(temp){
[1907]157      chat = new packet::Chat(message, playerID);
[1735]158      chat->setClientID(temp->getID());
159      if(!chat->send())
160        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
[1907]161      temp = temp->next();
[1735]162    }
[2087]163//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
[1907]164    return true;
[1502]165  }
166
167
[7756]168  /* handle incoming data */
[7739]169  int rephandler( char *addr, ENetEvent *ev )
170  { 
[7756]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;
[7739]179
180    /* done handling, return all ok code 0 */
181    return 0;
182  }
183
184  void Server::helper_HandleMasterServerRequests()
185  { 
[7750]186    /* poll the master server for replies and see whether something
187     * has to be done or changed.
188     */
[7763]189    //WANDiscovery::getInstance().msc.pollForReply( rhandler, 10 );
[7739]190  }
191
[1502]192  /**
193  * Run this function once every tick
194  * calls processQueue and updateGamestate
195  * @param time time since last tick
196  */
[7163]197  void Server::update(const Clock& time)
198  {
[3304]199    // receive incoming packets
[3214]200    Connection::processQueue();
[7739]201
[7163]202    // receive and process incoming discovery packets
203    LANDiscoverable::update();
[6417]204
[7739]205    // receive and process requests from master server
[7740]206    /* todo */
207    //helper_HandleMasterServerRequests();
[7739]208
[3304]209    if ( ClientInformation::hasClients() )
[3214]210    {
[3304]211      // process incoming gamestates
212      GamestateManager::processGamestates();
[6417]213
[3304]214      // send function calls to clients
[3084]215      FunctionCallManager::sendCalls();
[6417]216
[3304]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
[1502]225    }
226  }
[1747]227
[7163]228  bool Server::queuePacket(ENetPacket *packet, int clientID)
229  {
[3214]230    return ServerConnection::addPacket(packet, clientID);
[1735]231  }
[6417]232
[2087]233  /**
[6417]234   * @brief: returns ping time to client in milliseconds
[2087]235   */
[7163]236  unsigned int Server::getRTT(unsigned int clientID)
237  {
[2087]238    assert(ClientInformation::findClient(clientID));
239    return ClientInformation::findClient(clientID)->getRTT();
240  }
[6417]241
[5961]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  }
[1502]247
248  /**
[2087]249   * @brief: return packet loss ratio to client (scales from 0 to 1)
250   */
[7163]251  double Server::getPacketLoss(unsigned int clientID)
252  {
[2087]253    assert(ClientInformation::findClient(clientID));
254    return ClientInformation::findClient(clientID)->getPacketLoss();
255  }
[1502]256
257  /**
258  * takes a new snapshot of the gamestate and sends it to the clients
259  */
[7163]260  void Server::updateGamestate()
261  {
[3304]262    if( ClientInformation::getBegin()==NULL )
[2662]263      //no client connected
[3304]264      return;
265    GamestateManager::update();
[1534]266    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
[1502]267    //std::cout << "updated gamestate, sending it" << std::endl;
268    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
269    sendGameState();
[1907]270    sendObjectDeletes();
[1534]271    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
[1502]272    //std::cout << "sent gamestate" << std::endl;
273  }
274
[1735]275  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
276    packet::Packet *p = packet::Packet::createPacket(packet, peer);
277    return p->process();
278  }
[1747]279
[1502]280  /**
281  * sends the gamestate
282  */
[7163]283  bool Server::sendGameState()
284  {
[3304]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();
[1502]317    return true;
318  }
[1747]319
[7163]320  bool Server::sendObjectDeletes()
321  {
[1907]322    ClientInformation *temp = ClientInformation::getBegin();
[2662]323    if( temp == NULL )
324      //no client connected
325      return true;
[1907]326    packet::DeleteObjects *del = new packet::DeleteObjects();
327    if(!del->fetchIDs())
[5929]328    {
329      delete del;
[1907]330      return true;  //everything ok (no deletes this tick)
[5929]331    }
[1907]332//     COUT(3) << "sending DeleteObjects" << std::endl;
333    while(temp != NULL){
[7163]334      if( !(temp->getSynched()) )
335      {
[1907]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    }
[3198]349    delete del;
[1907]350    return true;
351  }
[1747]352
[1907]353
[7163]354  void Server::addPeer(ENetEvent *event)
355  {
[2087]356    static unsigned int newid=1;
357
358    COUT(2) << "Server: adding client" << std::endl;
[1735]359    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
[7163]360    if(!temp)
361    {
[1502]362      COUT(2) << "Server: could not add client" << std::endl;
363    }
[2087]364    temp->setID(newid);
[1502]365    temp->setPeer(event->peer);
[2087]366
367    // inform all the listeners
[5929]368    ClientConnectionListener::broadcastClientConnected(newid);
[2087]369
[3214]370    ++newid;
[2087]371
[1502]372    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
[3214]373    createClient(temp->getID());
[2087]374}
[1747]375
[5929]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 );
[5961]385      //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
[5929]386      delete client;
387    }
388  }
389
[7163]390  bool Server::createClient(int clientID)
391  {
[1735]392    ClientInformation *temp = ClientInformation::findClient(clientID);
[7163]393    if(!temp)
394    {
[1502]395      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
396      return false;
397    }
[3084]398    COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl;
[6417]399
[3084]400    // synchronise class ids
[3214]401    syncClassid(temp->getID());
[6417]402
[3084]403    // now synchronise functionIDs
404    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
405    fIDs->setClientID(clientID);
406    bool b = fIDs->send();
407    assert(b);
[6417]408
[1502]409    temp->setSynched(true);
[3084]410    COUT(4) << "sending welcome" << std::endl;
[1735]411    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
412    w->setClientID(temp->getID());
[3084]413    b = w->send();
[1907]414    assert(b);
[1751]415    packet::Gamestate *g = new packet::Gamestate();
416    g->setClientID(temp->getID());
[3102]417    b = g->collectData(0,0x1);
[2087]418    if(!b)
419      return false; //no data for the client
[1907]420    b = g->compressData();
421    assert(b);
422    b = g->send();
423    assert(b);
[1502]424    return true;
425  }
[6417]426
[7163]427  void Server::disconnectClient( ClientInformation *client )
428  {
[3214]429    ServerConnection::disconnectClient( client );
[3304]430    GamestateManager::removeClient(client);
[5929]431    // inform all the listeners
[5961]432    // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now
[1502]433  }
[2087]434
[7163]435  bool Server::chat(const std::string& message)
436  {
[2087]437      return this->sendChat(message, Host::getPlayerID());
438  }
439
[7163]440  bool Server::broadcast(const std::string& message)
441  {
[2087]442      return this->sendChat(message, CLIENTID_UNKNOWN);
443  }
444
[7163]445  bool Server::sendChat(const std::string& message, unsigned int clientID)
446  {
[1907]447    ClientInformation *temp = ClientInformation::getBegin();
448    packet::Chat *chat;
[7163]449    while(temp)
450    {
[2087]451      chat = new packet::Chat(message, clientID);
[1907]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    }
[2087]457//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
[2171]458    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
[2087]459      it->incomingChat(message, clientID);
460
[1907]461    return true;
462  }
[1747]463
[7163]464  void Server::syncClassid(unsigned int clientID)
465  {
[3214]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
[1502]476}
Note: See TracBrowser for help on using the repository browser.