Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

enet is not threadsafe (catched that now); some first step towards dedicated server

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