Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/network/ConnectionManager.cc @ 1389

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

some fixes in client disconnect procedure — mostly because of multithreading

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