Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

took out some mallocs and replaced them with new

File size: 12.4 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;
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          // add some error/log handling here
197          clientDisconnect(event.peer);
198          break;
199        case ENET_EVENT_TYPE_NONE:
200          break;
201      }
202    }
203    disconnectClients();
204    // if we're finishied, destroy server
205    enet_host_destroy(server);
206  }
207 
208  //### added some bugfixes here, but we cannot test them because
209  //### the server crashes everytime because of some gamestates
210  //### (trying to resolve that now)
211  void ConnectionManager::disconnectClients() {
212    ENetEvent event;
213    ClientInformation *temp = head_->next();
214    while(temp!=0){
215      enet_peer_disconnect(temp->getPeer(), 0);
216      temp = temp->next();
217    }
218    //bugfix: might be the reason why server crashes when clients disconnects
219    //temp = temp->next();
220    temp = head_->next();
221    while( temp!=0 && enet_host_service(server, &event, NETWORK_WAIT_TIMEOUT) > 0){
222      switch (event.type)
223      {
224      case ENET_EVENT_TYPE_NONE: break;
225      case ENET_EVENT_TYPE_CONNECT: break;
226      case ENET_EVENT_TYPE_RECEIVE:
227        enet_packet_destroy(event.packet);
228        break;
229      case ENET_EVENT_TYPE_DISCONNECT:
230        COUT(4) << "disconnecting all clients" << std::endl;
231        delete head_->findClient(&(event.peer->address));
232        //maybe needs bugfix: might also be a reason for the server to crash
233        temp = temp->next();
234        break;
235      }
236    }
237    return;
238  }
239
240  bool ConnectionManager::processData(ENetEvent *event) {
241    // just add packet to the buffer
242    // this can be extended with some preprocessing
243    return buffer.push(event);
244  }
245
246  bool ConnectionManager::clientDisconnect(ENetPeer *peer) {
247    COUT(4) << "removing client from list" << std::endl;
248    return head_->removeClient(peer);
249  }
250/**
251This function adds a client that connects to the clientlist of the server
252NOTE: if you change this, don't forget to change the test function
253addClientTest in diffTest.cc since addClient is not good for testing because of syncClassid
254*/
255  bool ConnectionManager::addClient(ENetEvent *event) {
256    ClientInformation *temp = head_->insertBack(new ClientInformation);
257    if(temp->prev()->head) { //not good if you use anything else than insertBack
258      temp->prev()->setID(0); //bugfix: not necessary but usefull
259      temp->setID(1);
260    }
261    else
262      temp->setID(temp->prev()->getID()+1);
263    temp->setPeer(event->peer);
264    COUT(4) << "Con.Man: added client id: " << temp->getID() << std::endl;
265    return true;
266  }
267
268  int ConnectionManager::getClientID(ENetPeer peer) {
269    return getClientID(peer.address);
270  }
271
272  int ConnectionManager::getClientID(ENetAddress address) {
273    return head_->findClient(&address)->getID();
274  }
275
276  ENetPeer *ConnectionManager::getClientPeer(int clientID) {
277    return head_->findClient(clientID)->getPeer();
278  }
279
280  void ConnectionManager::syncClassid(int clientID) {
281    unsigned int network_id=0;
282    std::string classname;
283    orxonox::Identifier *id;
284    std::map<std::string, orxonox::Identifier*>::const_iterator it = orxonox::Factory::getFactoryBegin();
285    while(it != orxonox::Factory::getFactoryEnd()){
286      id = (*it).second;
287      if(id == NULL)
288        continue;
289      classname = id->getName();
290      network_id = id->getNetworkID();
291      COUT(4) << "Con.Man:syncClassid:\tnetwork_id: " << network_id << ", classname: " << classname << std::endl;
292
293      addPacket(packet_gen.clid( (int)network_id, classname ), clientID);
294
295      ++it;
296    }
297    sendPackets();
298    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
299  }
300
301  bool ConnectionManager::createClient(int clientID){
302    ClientInformation *temp = head_->findClient(clientID);
303    COUT(4) << "Con.Man: creating client id: " << temp->getID() << std::endl;
304    syncClassid(temp->getID());
305    COUT(4) << "creating spaceship for clientid: " << temp->getID() << std::endl;
306    // TODO: this is only a hack, untill we have a possibility to define default player-join actions
307    createShip(temp);
308    COUT(4) << "created spaceship" << std::endl;
309    temp->setSynched(true);
310    COUT(4) << "sending welcome" << std::endl;
311    sendWelcome(temp->getID(), temp->getShipID(), true);
312    return true;
313  }
314 
315  bool ConnectionManager::createShip(ClientInformation *client){
316    orxonox::Identifier* id = ID("SpaceShip");
317    if(!id){
318      COUT(4) << "We could not create the SpaceShip for client: " << client->getID() << std::endl;
319      return false;
320    }
321    orxonox::SpaceShip *no = dynamic_cast<orxonox::SpaceShip *>(id->fabricate());
322    no->setPosition(orxonox::Vector3(0,80,0));
323    no->setScale(10);
324    no->setYawPitchRoll(orxonox::Degree(-90),orxonox::Degree(-90),orxonox::Degree(0));
325    no->setMesh("assf3.mesh");
326    no->setMaxSpeed(500);
327    no->setMaxSideAndBackSpeed(50);
328    no->setMaxRotation(1.0);
329    no->setTransAcc(200);
330    no->setRotAcc(3.0);
331    no->setTransDamp(75);
332    no->setRotDamp(1.0);
333    no->setCamera("cam_"+client->getID());
334    no->create();
335   
336    client->setShipID(no->objectID);
337    return true;
338  }
339 
340  bool ConnectionManager::sendWelcome(int clientID, int shipID, bool allowed){
341    addPacket(packet_gen.generateWelcome(clientID, shipID, allowed),clientID);
342    sendPackets();
343  }
344 
345  bool ConnectionManager::addFakeConnectRequest(ENetEvent *ev){
346    ENetEvent event;
347    event.peer=ev->peer;
348    event.packet = packet_gen.generateConnectRequest();
349    return buffer.push(&event);
350  }
351 
352 
353//   int ConnectionManager::getNumberOfClients() {
354//     
355//     return clientsShip.size();
356//   }
357 
358  /*void ConnectionManager::addClientsObjectID( int clientID, int objectID ) {
359  COUT(4) << "ship of client: " << clientID << ": " << objectID << " mapped" << std::endl;
360  clientsShip.insert( std::make_pair( clientID, objectID ) );
361}
362
363  int ConnectionManager::getClientsShipID( int clientID ) {
364  return clientsShip[clientID];
365}
366
367  int ConnectionManager::getObjectsClientID( int objectID ) {
368  std::map<int, int>::iterator iter;
369  for( iter = clientsShip.begin(); iter != clientsShip.end(); iter++ ) {
370  if( iter->second == objectID ) return iter->first;
371}
372  return -99;
373}
374
375  void ConnectionManager::deleteClientIDReg( int clientID ) {
376  clientsShip.erase( clientID );
377}
378
379  void ConnectionManager::deleteObjectIDReg( int objectID ) {
380  std::map<int, int>::iterator iter = clientsShip.begin();
381  for( iter = clientsShip.begin(); iter != clientsShip.end(); iter++ ) {
382  if( iter->second == objectID ) break;
383}
384  clientsShip.erase( iter->first );
385}*/
386}
Note: See TracBrowser for help on using the repository browser.