Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

changed concept of threading, had to change packetbuffer (using events now)

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