Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

various enhancements with enet handling (serverside in
connectionmanager)

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