Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network3/src/network/ConnectionManager.cc @ 1250

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

memory free problem

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