Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

we are now able to manage multiple clients ;)

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