Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/netp6/src/network/Server.cc @ 3284

Last change on this file since 3284 was 3240, checked in by scheusso, 16 years ago

a lot of cleanup
some bugfixes (Thread, ThreadPool)
the biggest part of the network (~80% cpu time) is now multithreaded (1 thread for each client)

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