Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/network/ConnectionManager.cc @ 1438

Last change on this file since 1438 was 1360, checked in by rgrieder, 17 years ago

merged merge branch back to trunk

File size: 14.2 KB
RevLine 
[1282]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++ Interface: ConnectionManager
31//
32// Description: The Class ConnectionManager manages the servers conenctions to the clients.
33// each connection is provided by a new process. communication between master process and
34// connection processes is provided by ...
35//
36//
37// Author:  Oliver Scheuss
38//
39
40#include <iostream>
41// boost.thread library for multithreading support
42#include <boost/bind.hpp>
43
44#include "core/CoreIncludes.h"
45#include "core/BaseObject.h"
46#include "util/Math.h"
47#include "objects/SpaceShip.h"
48#include "ClientInformation.h"
49#include "ConnectionManager.h"
50#include "Synchronisable.h"
51
52namespace std
53{
54  bool operator< (ENetAddress a, ENetAddress b) {
55    if(a.host <= b.host)
56      return true;
57    else
58      return false;
59  }
60}
61
62namespace network
63{
64  //boost::thread_group network_threads;
65 
66  ConnectionManager::ConnectionManager():receiverThread_(0){}
67 
68  ConnectionManager::ConnectionManager(ClientInformation *head) : receiverThread_(0) {
69    quit=false;
70    bindAddress.host = ENET_HOST_ANY;
71    bindAddress.port = NETWORK_PORT;
72    head_ = head;
73  }
74
75  ConnectionManager::ConnectionManager(int port, std::string address, ClientInformation *head) :receiverThread_(0) {
76    quit=false;
77    enet_address_set_host (& bindAddress, address.c_str());
78    bindAddress.port = NETWORK_PORT;
79    head_ = head;
80  }
81
82  ConnectionManager::ConnectionManager(int port, const char *address, ClientInformation *head) : receiverThread_(0) {
83    quit=false;
84    enet_address_set_host (& bindAddress, address);
85    bindAddress.port = NETWORK_PORT;
86    head_ = head;
87  }
88
89  ENetPacket *ConnectionManager::getPacket(ENetAddress &address) {
90    if(!buffer.isEmpty())
91      return buffer.pop(address);
92    else
93      return NULL;
94  }
95/**
96This function only pops the first element in PacketBuffer (first in first out)
97used by processQueue in Server.cc
98*/
99  ENetPacket *ConnectionManager::getPacket(int &clientID) {
100    ENetAddress address;
101    ENetPacket *packet=getPacket(address);
102    ClientInformation *temp =head_->findClient(&address);
[1360]103    if(!temp)
104      return NULL;
[1282]105    clientID=temp->getID();
106    return packet;
107  }
108
109  bool ConnectionManager::queueEmpty() {
110    return buffer.isEmpty();
111  }
112
113  void ConnectionManager::createListener() {
114    receiverThread_ = new boost::thread(boost::bind(&ConnectionManager::receiverThread, this));
115    //network_threads.create_thread(boost::bind(boost::mem_fn(&ConnectionManager::receiverThread), this));
116         //boost::thread thr(boost::bind(boost::mem_fn(&ConnectionManager::receiverThread), this));
117    return;
118  }
119
120  bool ConnectionManager::quitListener() {
121    quit=true;
122    //network_threads.join_all();
123    receiverThread_->join();
124    return true;
125  }
126
127  bool ConnectionManager::addPacket(ENetPacket *packet, ENetPeer *peer) {
[1360]128    ClientInformation *temp = head_->findClient(&(peer->address));
129    if(!temp)
[1282]130      return false;
[1360]131    if(enet_peer_send(peer, (enet_uint8)temp->getID() , packet)!=0)
132      return false;
[1282]133    return true;
134  }
135
136  bool ConnectionManager::addPacket(ENetPacket *packet, int clientID) {
[1360]137    ClientInformation *temp = head_->findClient(clientID);
138    if(!temp)
[1282]139      return false;
[1360]140    if(enet_peer_send(temp->getPeer(), (enet_uint8)clientID, packet)!=0)
141      return false;
[1282]142    return true;
143  }
144
145  bool ConnectionManager::addPacketAll(ENetPacket *packet) {
146    for(ClientInformation *i=head_->next(); i!=0; i=i->next()){
147      if(enet_peer_send(i->getPeer(), (enet_uint8)i->getID(), packet)!=0)
148        return false;
149    }
150    return true;
151  }
152
153  bool ConnectionManager::sendPackets(ENetEvent *event) {
154    if(server==NULL)
155      return false;
156    if(enet_host_service(server, event, NETWORK_SEND_WAIT)>=0)
157      return true;
158    else
159      return false;
160  }
161
162  bool ConnectionManager::sendPackets() {
163    ENetEvent event;
164    if(server==NULL)
165      return false;
166    if(enet_host_service(server, &event, NETWORK_SEND_WAIT)>=0)
167      return true;
168    else
169      return false;
170  }
171
172  void ConnectionManager::receiverThread() {
173    // what about some error-handling here ?
174    enet_initialize();
175    atexit(enet_deinitialize);
176    ENetEvent *event = new ENetEvent;
177    server = enet_host_create(&bindAddress, NETWORK_MAX_CONNECTIONS, 0, 0);
178    if(server==NULL){
179      // add some error handling here ==========================
180      quit=true;
181      return;
182    }
183
184    while(!quit){
185      if(enet_host_service(server, event, NETWORK_WAIT_TIMEOUT)<0){
186        // we should never reach this point
187        quit=true;
188        // add some error handling here ========================
189      }
190      switch(event->type){
191        // log handling ================
192        case ENET_EVENT_TYPE_CONNECT:
193          addClient(event);
194          //this is a workaround to ensure thread safety
195          COUT(5) << "Con.Man: connection event has occured" << std::endl;
196          break;
197        case ENET_EVENT_TYPE_RECEIVE:
198          //std::cout << "received data" << std::endl;
199          COUT(5) << "Con.Man: receive event has occured" << std::endl;
200          // only add, if client has connected yet and not been disconnected
201          if(head_->findClient(&event->peer->address))
202            processData(event);
[1360]203          else
204            COUT(3) << "received a packet from a client we don't know" << std::endl;
[1282]205          break;
206        case ENET_EVENT_TYPE_DISCONNECT:
207          clientDisconnect(event->peer);
208          break;
209        case ENET_EVENT_TYPE_NONE:
[1360]210          receiverThread_->yield();
[1282]211          break;
212      }
213//       usleep(100);
214      receiverThread_->yield(); //TODO: find apropriate
215    }
216    disconnectClients();
217    // if we're finishied, destroy server
218    enet_host_destroy(server);
219  }
220 
221  //### added some bugfixes here, but we cannot test them because
222  //### the server crashes everytime because of some gamestates
223  //### (trying to resolve that now)
224  void ConnectionManager::disconnectClients() {
225    ENetEvent event;
226    ClientInformation *temp = head_->next();
227    while(temp!=0){
228      enet_peer_disconnect(temp->getPeer(), 0);
229      temp = temp->next();
230    }
231    //bugfix: might be the reason why server crashes when clients disconnects
232    //temp = temp->next();
233    temp = head_->next();
234    while( temp!=0 && enet_host_service(server, &event, NETWORK_WAIT_TIMEOUT) > 0){
235      switch (event.type)
236      {
237      case ENET_EVENT_TYPE_NONE: break;
238      case ENET_EVENT_TYPE_CONNECT: break;
239      case ENET_EVENT_TYPE_RECEIVE:
240        enet_packet_destroy(event.packet);
241        break;
242      case ENET_EVENT_TYPE_DISCONNECT:
243        COUT(4) << "disconnecting all clients" << std::endl;
[1360]244        if(head_->findClient(&(event.peer->address)))
245          delete head_->findClient(&(event.peer->address));
[1282]246        //maybe needs bugfix: might also be a reason for the server to crash
247        temp = temp->next();
248        break;
249      }
250    }
251    return;
252  }
253
254  bool ConnectionManager::processData(ENetEvent *event) {
255    // just add packet to the buffer
256    // this can be extended with some preprocessing
257    return buffer.push(event);
258  }
259
260  bool ConnectionManager::clientDisconnect(ENetPeer *peer) {
261    COUT(4) << "removing client from list" << std::endl;
262    return removeClient(head_->findClient(&(peer->address))->getID());
263  }
264/**
265This function adds a client that connects to the clientlist of the server
266NOTE: if you change this, don't forget to change the test function
267addClientTest in diffTest.cc since addClient is not good for testing because of syncClassid
268*/
269  bool ConnectionManager::addClient(ENetEvent *event) {
270    ClientInformation *temp = head_->insertBack(new ClientInformation);
[1360]271    if(!temp){
272      COUT(2) << "Conn.Man. could not add client" << std::endl;
273      return false;
274    }
275    if(temp->prev()->getHead()) { //not good if you use anything else than insertBack
[1282]276      temp->prev()->setID(0); //bugfix: not necessary but usefull
277      temp->setID(1);
278    }
279    else
280      temp->setID(temp->prev()->getID()+1);
281    temp->setPeer(event->peer);
[1360]282    COUT(3) << "Con.Man: added client id: " << temp->getID() << std::endl;
[1282]283    return true;
284  }
285
286  int ConnectionManager::getClientID(ENetPeer peer) {
287    return getClientID(peer.address);
288  }
289
290  int ConnectionManager::getClientID(ENetAddress address) {
291    return head_->findClient(&address)->getID();
292  }
293
294  ENetPeer *ConnectionManager::getClientPeer(int clientID) {
295    return head_->findClient(clientID)->getPeer();
296  }
297
298  void ConnectionManager::syncClassid(int clientID) {
[1360]299    unsigned int network_id=0, failures=0;
[1282]300    std::string classname;
301    orxonox::Identifier *id;
302    std::map<std::string, orxonox::Identifier*>::const_iterator it = orxonox::Factory::getFactoryBegin();
303    while(it != orxonox::Factory::getFactoryEnd()){
304      id = (*it).second;
305      if(id == NULL)
306        continue;
307      classname = id->getName();
308      network_id = id->getNetworkID();
[1360]309      if(network_id==0)
310        COUT(3) << "we got a null class id: " << id->getName() << std::endl;
[1282]311      COUT(4) << "Con.Man:syncClassid:\tnetwork_id: " << network_id << ", classname: " << classname << std::endl;
312
[1360]313      while(!addPacket(packet_gen.clid( (int)network_id, classname ), clientID) && failures < 10){
314        failures++;
315      }
[1282]316      ++it;
317    }
318    sendPackets();
319    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
320  }
321
322  bool ConnectionManager::createClient(int clientID){
323    ClientInformation *temp = head_->findClient(clientID);
[1360]324    if(!temp){
325      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
326      return false;
327    }
[1282]328    COUT(4) << "Con.Man: creating client id: " << temp->getID() << std::endl;
329    syncClassid(temp->getID());
330    COUT(4) << "creating spaceship for clientid: " << temp->getID() << std::endl;
331    // TODO: this is only a hack, untill we have a possibility to define default player-join actions
[1360]332    if(!createShip(temp))
333      COUT(2) << "Con.Man. could not create ship for clientid: " << clientID << std::endl;
334    else
335      COUT(3) << "created spaceship" << std::endl;
[1282]336    temp->setSynched(true);
[1360]337    COUT(3) << "sending welcome" << std::endl;
[1282]338    sendWelcome(temp->getID(), temp->getShipID(), true);
339    return true;
340  }
341 
342  bool ConnectionManager::removeClient(int clientID){
343    orxonox::Iterator<orxonox::SpaceShip> it = orxonox::ObjectList<orxonox::SpaceShip>::start();
[1360]344    ClientInformation *client = head_->findClient(clientID);
345    if(!client)
346      return false;
[1282]347    while(it){
[1360]348      if(it->objectID!=client->getShipID()){
[1282]349        ++it;
350        continue;
351      }
352      orxonox::Iterator<orxonox::SpaceShip> temp=it;
353      ++it;
354      delete  *temp;
355      return head_->removeClient(clientID);
356    }
357    return false;
358  }
359 
360  bool ConnectionManager::createShip(ClientInformation *client){
[1360]361    if(!client)
362      return false;
[1282]363    orxonox::Identifier* id = ID("SpaceShip");
364    if(!id){
365      COUT(4) << "We could not create the SpaceShip for client: " << client->getID() << std::endl;
366      return false;
367    }
368    orxonox::SpaceShip *no = dynamic_cast<orxonox::SpaceShip *>(id->fabricate());
369    no->setPosition(orxonox::Vector3(0,80,0));
370    no->setScale(10);
371    no->setYawPitchRoll(orxonox::Degree(-90),orxonox::Degree(-90),orxonox::Degree(0));
372    no->setMesh("assff.mesh");
373    no->setMaxSpeed(500);
374    no->setMaxSideAndBackSpeed(50);
375    no->setMaxRotation(1.0);
376    no->setTransAcc(200);
377    no->setRotAcc(3.0);
378    no->setTransDamp(75);
379    no->setRotDamp(1.0);
380    no->setCamera("cam_"+client->getID());
[1360]381    no->classID = id->getNetworkID();
[1282]382    no->create();
383   
384    client->setShipID(no->objectID);
385    return true;
386  }
387 
388  bool ConnectionManager::removeShip(ClientInformation *client){
389    int id=client->getShipID();
390    orxonox::Iterator<orxonox::SpaceShip> it;
391    for(it = orxonox::ObjectList<orxonox::SpaceShip>::start(); it; ++it){
392      if(it->objectID!=id)
393        continue;
394      delete *it;
395    }
396    return true;
397  }
398 
399  bool ConnectionManager::sendWelcome(int clientID, int shipID, bool allowed){
[1360]400    if(addPacket(packet_gen.generateWelcome(clientID, shipID, allowed),clientID)){
401      sendPackets();
402      return true;
403    }else
404      return false;
[1282]405  }
406 
407  void ConnectionManager::disconnectClient(ClientInformation *client){
408    enet_peer_disconnect(client->getPeer(), 0);
409    removeShip(client);
410  }
411 
412  bool ConnectionManager::addFakeConnectRequest(ENetEvent *ev){
413    ENetEvent event;
414    event.peer=ev->peer;
415    event.packet = packet_gen.generateConnectRequest();
416    return buffer.push(&event);
417  }
418 
419 
420//   int ConnectionManager::getNumberOfClients() {
421//     
422//     return clientsShip.size();
423//   }
424 
425  /*void ConnectionManager::addClientsObjectID( int clientID, int objectID ) {
426  COUT(4) << "ship of client: " << clientID << ": " << objectID << " mapped" << std::endl;
427  clientsShip.insert( std::make_pair( clientID, objectID ) );
428}
429
430  int ConnectionManager::getClientsShipID( int clientID ) {
431  return clientsShip[clientID];
432}
433
434  int ConnectionManager::getObjectsClientID( int objectID ) {
435  std::map<int, int>::iterator iter;
436  for( iter = clientsShip.begin(); iter != clientsShip.end(); iter++ ) {
437  if( iter->second == objectID ) return iter->first;
438}
439  return -99;
440}
441
442  void ConnectionManager::deleteClientIDReg( int clientID ) {
443  clientsShip.erase( clientID );
444}
445
446  void ConnectionManager::deleteObjectIDReg( int objectID ) {
447  std::map<int, int>::iterator iter = clientsShip.begin();
448  for( iter = clientsShip.begin(); iter != clientsShip.end(); iter++ ) {
449  if( iter->second == objectID ) break;
450}
451  clientsShip.erase( iter->first );
452}*/
453}
Note: See TracBrowser for help on using the repository browser.