Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

some speed enhancements regarding to mutexes in enet send/receive mechanisms

  • Property svn:eol-style set to native
File size: 11.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 "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  // we actually dont need that function, because host_service does that for us
172  bool ConnectionManager::sendPackets() {
173    if(server==NULL)
174      return false;
175    boost::recursive_mutex::scoped_lock lock(enet_mutex_);
176    enet_host_flush(server);
177    lock.unlock();
178    return true;
179  }
180
181  void ConnectionManager::receiverThread() {
182    // what about some error-handling here ?
183    ENetEvent *event;
184    atexit(enet_deinitialize);
185    { //scope of the mutex
186      boost::recursive_mutex::scoped_lock lock(enet_mutex_);
187      enet_initialize();
188      server = enet_host_create(&bindAddress, NETWORK_MAX_CONNECTIONS, 0, 0);
189      lock.unlock();
190    }
191    if(server==NULL){
192      // add some error handling here ==========================
193      quit=true;
194      return;
195    }
196
197    event = new ENetEvent;
198    while(!quit){
199      { //mutex scope
200        boost::recursive_mutex::scoped_lock lock(enet_mutex_);
201        if(enet_host_service(server, event, NETWORK_WAIT_TIMEOUT)<0){
202          // we should never reach this point
203          quit=true;
204          continue;
205          // add some error handling here ========================
206        }
207        lock.unlock();
208      }
209      switch(event->type){
210        // log handling ================
211        case ENET_EVENT_TYPE_CONNECT:
212          COUT(3) << "adding event_type_connect to queue" << std::endl;
213        case ENET_EVENT_TYPE_DISCONNECT:
214          //addClient(event);
215          //this is a workaround to ensure thread safety
216          //COUT(5) << "Con.Man: connection event has occured" << std::endl;
217          //break;
218        case ENET_EVENT_TYPE_RECEIVE:
219          //std::cout << "received data" << std::endl;
220          COUT(5) << "Con.Man: receive event has occured" << std::endl;
221          // only add, if client has connected yet and not been disconnected
222          //if(head_->findClient(&event->peer->address))
223            processData(event);
224            event = new ENetEvent;
225//           else
226//             COUT(3) << "received a packet from a client we don't know" << std::endl;
227          break;
228        //case ENET_EVENT_TYPE_DISCONNECT:
229          //clientDisconnect(event->peer);
230          //break;
231        case ENET_EVENT_TYPE_NONE:
232          //receiverThread_->yield();
233          usleep(1000);
234          break;
235      }
236//       usleep(100);
237      //receiverThread_->yield(); //TODO: find apropriate
238    }
239    disconnectClients();
240    // if we're finishied, destroy server
241    {
242      boost::recursive_mutex::scoped_lock lock(enet_mutex_);
243      enet_host_destroy(server);
244      lock.unlock();
245    }
246  }
247 
248  //### added some bugfixes here, but we cannot test them because
249  //### the server crashes everytime because of some gamestates
250  //### (trying to resolve that now)
251  void ConnectionManager::disconnectClients() {
252    ENetEvent event;
253    ClientInformation *temp = head_->next();
254    while(temp!=0){
255      {
256        boost::recursive_mutex::scoped_lock lock(enet_mutex_);
257        enet_peer_disconnect(temp->getPeer(), 0);
258        lock.unlock();
259      }
260      temp = temp->next();
261    }
262    //bugfix: might be the reason why server crashes when clients disconnects
263    temp = head_->next();
264    boost::recursive_mutex::scoped_lock lock(enet_mutex_);
265    while( temp!=0 && enet_host_service(server, &event, NETWORK_WAIT_TIMEOUT) >= 0){
266      switch (event.type)
267      {
268      case ENET_EVENT_TYPE_NONE: break;
269      case ENET_EVENT_TYPE_CONNECT: break;
270      case ENET_EVENT_TYPE_RECEIVE:
271        enet_packet_destroy(event.packet);
272        break;
273      case ENET_EVENT_TYPE_DISCONNECT:
274        COUT(4) << "disconnecting all clients" << std::endl;
275        if(head_->findClient(&(event.peer->address)))
276          delete head_->findClient(&(event.peer->address));
277        //maybe needs bugfix: might also be a reason for the server to crash
278        temp = temp->next();
279        break;
280      }
281    }
282    return;
283  }
284
285  bool ConnectionManager::processData(ENetEvent *event) {
286    // just add packet to the buffer
287    // this can be extended with some preprocessing
288    return buffer.push(event);
289  }
290
291
292
293  int ConnectionManager::getClientID(ENetPeer peer) {
294    return getClientID(peer.address);
295  }
296
297  int ConnectionManager::getClientID(ENetAddress address) {
298    return head_->findClient(&address)->getID();
299  }
300
301  ENetPeer *ConnectionManager::getClientPeer(int clientID) {
302    return head_->findClient(clientID)->getPeer();
303  }
304
305  void ConnectionManager::syncClassid(int clientID) {
306    unsigned int network_id=0, failures=0;
307    std::string classname;
308    orxonox::Identifier *id;
309    std::map<std::string, orxonox::Identifier*>::const_iterator it = orxonox::Factory::getFactoryBegin();
310    while(it != orxonox::Factory::getFactoryEnd()){
311      id = (*it).second;
312      if(id == NULL)
313        continue;
314      classname = id->getName();
315      network_id = id->getNetworkID();
316      if(network_id==0)
317        COUT(3) << "we got a null class id: " << id->getName() << std::endl;
318      COUT(4) << "Con.Man:syncClassid:\tnetwork_id: " << network_id << ", classname: " << classname << std::endl;
319
320      while(!addPacket(packet_gen.clid( (int)network_id, classname ), clientID) && failures < 10){
321        failures++;
322      }
323      ++it;
324    }
325    //sendPackets();
326    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
327  }
328
329 
330 
331  bool ConnectionManager::removeShip(ClientInformation *client){
332    int id=client->getShipID();
333    orxonox::Iterator<orxonox::SpaceShip> it;
334    for(it = orxonox::ObjectList<orxonox::SpaceShip>::start(); it; ++it){
335      if(it->objectID!=id)
336        continue;
337      delete *it;
338    }
339    return true;
340  }
341 
342  bool ConnectionManager::sendWelcome(int clientID, int shipID, bool allowed){
343    if(addPacket(packet_gen.generateWelcome(clientID, shipID, allowed),clientID)){
344      //sendPackets();
345      return true;
346    }else
347      return false;
348  }
349 
350  void ConnectionManager::disconnectClient(ClientInformation *client){
351    {
352      boost::recursive_mutex::scoped_lock lock(enet_mutex_);
353      enet_peer_disconnect(client->getPeer(), 0);
354      lock.unlock();
355    }
356    removeShip(client);
357  }
358 
359  bool ConnectionManager::addFakeConnectRequest(ENetEvent *ev){
360    ENetEvent event;
361    event.peer=ev->peer;
362    event.packet = packet_gen.generateConnectRequest();
363    return buffer.push(&event);
364  }
365 
366 
367
368}
Note: See TracBrowser for help on using the repository browser.