Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/netp5/src/network/Server.cc @ 3201

Last change on this file since 3201 was 3201, checked in by scheusso, 15 years ago

cleaned up server connection handling
client is yet to come

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