Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/objecthierarchy/src/network/Server.cc @ 1953

Last change on this file since 1953 was 1953, checked in by landauf, 16 years ago

added chat overlay

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