Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/network/src/lib/network/network_stream.cc @ 6678

Last change on this file since 6678 was 6678, checked in by patrick, 18 years ago

network: sys better now, got less errors and removed the pnode link sync alg, replacing

File size: 11.8 KB
RevLine 
[5566]1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11### File Specific:
[5601]12   main-programmer: claudio
[5800]13   co-programmer:
[5566]14*/
15
16
17/* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
18   For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
19*/
20#define DEBUG_MODULE_NETWORK
21
[5747]22
[5647]23#include "base_object.h"
[5731]24#include "network_protocol.h"
[5647]25#include "network_socket.h"
26#include "connection_monitor.h"
27#include "synchronizeable.h"
[6139]28#include "network_manager.h"
[6341]29#include "network_game_manager.h"
30
[5649]31#include "debug.h"
[6139]32#include "class_list.h"
[6144]33#include <algorithm>
[5647]34
[5566]35/* include your own header */
36#include "network_stream.h"
37
[5595]38/* probably unnecessary */
[5594]39using namespace std;
40
[5595]41
[5747]42#define PACKAGE_SIZE  256
[5647]43
[5747]44
[5800]45NetworkStream::NetworkStream()
[5996]46    : DataStream()
[5647]47{
48  this->init();
[5648]49  /* initialize the references */
[5996]50  this->type = NET_CLIENT;
[5741]51  this->networkProtocol = new NetworkProtocol();
[5648]52  this->connectionMonitor = new ConnectionMonitor();
[5647]53}
54
[6660]55
[6139]56NetworkStream::NetworkStream(IPaddress& address)
[5996]57{
[6139]58  this->type = NET_CLIENT;
[5996]59  this->init();
[6139]60  this->networkSockets.push_back(new NetworkSocket(address));
[5996]61  this->networkProtocol = new NetworkProtocol();
62  this->connectionMonitor = new ConnectionMonitor();
[6341]63  this->maxConnections = 1;
[5996]64}
65
66
[6139]67NetworkStream::NetworkStream(unsigned int port)
[5647]68{
[6139]69  this->type = NET_SERVER;
[5647]70  this->init();
[6139]71  this->serverSocket = new ServerSocket(port);
[5741]72  this->networkProtocol = new NetworkProtocol();
73  this->connectionMonitor = new ConnectionMonitor();
[6139]74  this->networkSockets.push_back( NULL );
[6634]75  this->networkSockets[0] = NULL; //TODO: remove this
[6139]76  this->handshakes.push_back( NULL );
[5996]77  this->bActive = true;
[5649]78}
79
80
[5647]81void NetworkStream::init()
82{
83  /* set the class id for the base object */
84  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
[5996]85  this->bActive = false;
[6139]86  this->serverSocket = NULL;
[6341]87  this->networkGameManager = NULL;
[6139]88  myHostId = 0;
[5594]89}
90
[5647]91
[5566]92NetworkStream::~NetworkStream()
[5598]93{
[6139]94  if ( this->serverSocket )
95  {
96    serverSocket->close();
97    delete serverSocket;
98  }
[5723]99
[6139]100  for (NetworkSocketVector::iterator i = networkSockets.begin(); i!=networkSockets.end(); i++)
101  {
102    if ( *i )
103    {
104      (*i)->disconnectServer();
105      (*i)->destroy();
106    }
107  }
[5723]108
[6139]109  for (HandshakeVector::iterator i = handshakes.begin(); i!=handshakes.end(); i++)
110  {
111    if ( *i )
112    {
113      delete (*i);
114    }
115  }
[5805]116
[5996]117  delete connectionMonitor;
118  delete networkProtocol;
[5598]119}
120
[5996]121
[6659]122void NetworkStream::createNetworkGameManager()
123{
124  this->networkGameManager = NetworkGameManager::getInstance();
125  // setUniqueID( maxCon+2 ) because we need one id for every handshake
126  // and one for handshake to reject client maxCon+1
127  this->networkGameManager->setUniqueID( this->maxConnections + 2 );
[6661]128  //this->connectSynchronizeable( *(this->networkGameManager) );
[6659]129  this->setMaxConnections( 10 );
130}
131
132
[6660]133void NetworkStream::startHandshake()
134{
135  Handshake* hs = new Handshake(false);
136  hs->setUniqueID( 0 );
137  this->handshakes.push_back(hs);
138  //this->connectSynchronizeable(*hs);
139  PRINTF(0)("NetworkStream: %s\n", hs->getName());
140}
141
142
[5996]143void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
144{
[6139]145  this->synchronizeables.push_back(&sync);
146  sync.setNetworkStream( this );
147
148  if( this->networkSockets.size()>0 )
[5996]149    this->bActive = true;
150}
151
[6658]152
[6139]153void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
154{
[6144]155  // removing the Synchronizeable from the List.
156  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
157  if (disconnectSynchro != this->synchronizeables.end())
158    this->synchronizeables.erase(disconnectSynchro);
[5996]159
[6139]160  if( this->networkSockets.size()<=0 )
161    this->bActive = false;
162}
163
164
[5604]165void NetworkStream::processData()
166{
[6139]167  if ( this->type == NET_SERVER )
168    this->updateConnectionList();
169  else
170  {
171    if ( networkSockets[0] && !networkSockets[0]->isOk() )
172    {
173      PRINTF(1)("lost connection to server\n");
[5741]174
[6139]175      //delete networkSockets[i];
176      networkSockets[0]->disconnectServer();
177      networkSockets[0]->destroy();
178      networkSockets[0] = NULL;
[6498]179
[6139]180      if ( handshakes[0] )
181        delete handshakes[0];
182      handshakes[0] = NULL;
183    }
184  }
185
186  for (int i = 0; i<handshakes.size(); i++)
187  {
188    if ( handshakes[i] )
189    {
190      if ( handshakes[i]->completed() )
191      {
192        if ( handshakes[i]->ok() )
193        {
194          if ( type != NET_SERVER )
195          {
[6678]196            SharedNetworkData::getInstance()->setHostID( handshakes[i]->getHostId() );
[6139]197            myHostId = NetworkManager::getInstance()->getHostID();
[6341]198
199            this->networkGameManager = NetworkGameManager::getInstance();
200            this->networkGameManager->setUniqueID( handshakes[i]->getNetworkGameManagerId() );
[6661]201            //this->connectSynchronizeable( *(this->networkGameManager) );
[6139]202          }
[6341]203          else
204          {
[6498]205
[6341]206          }
207          PRINT(0)("handshake finished id=%d\n", handshakes[i]->getNetworkGameManagerId());
208
209
[6139]210          delete handshakes[i];
211          handshakes[i] = NULL;
212        }
213        else
214        {
215          PRINT(1)("handshake failed!\n");
216          networkSockets[i]->disconnectServer();
217          delete handshakes[i];
218          handshakes[i] = NULL;
219          //TODO: handle error
220        }
221      }
222    }
223  }
224
225
[5650]226  /* DOWNSTREAM */
[5800]227
[6658]228
229
[6139]230  int dataLength;
231  int reciever;
232  Header header;
233  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
[5996]234  {
[6658]235    if ( (*it)!=NULL && (*it)->beSynchronized() /*&& (*it)->getOwner() == myHostId*/ )
[6139]236    {
237      do {
238        reciever = 0;
239        dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
[5730]240
[5800]241
[6139]242        if ( dataLength<=0 ){
243          reciever = 0;
244          continue;
245        }
246
247        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
248
249        Header* header = (Header*)downBuffer;
[6341]250        if ( header->synchronizeableID < this->maxConnections+2 )
251        {
252          //if ( !isServer() ) PRINTF(0)("RESET UNIQUEID FROM %d TO 0 maxCon=%d\n", header->synchronizeableID, this->maxConnections);
[6139]253          header->synchronizeableID = 0;
[6341]254        }
255        else
256        {
257          //if ( !isServer() ) PRINTF(0)("UNIQUEID=%d\n", header->synchronizeableID);
258        }
[6139]259
260        if ( dataLength<=0 )
261          continue;
262
263        if ( reciever!=0 )
264        {
265          if ( networkSockets[reciever] != NULL )
266          {
[6498]267            PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
[6139]268            networkSockets[reciever]->writePacket(downBuffer, dataLength);
269          }
270          else
271          {
272            PRINTF(1)("networkSockets[reciever] == NULL\n");
273          }
274        }
275        else
276        {
277          for ( int i = 0; i<networkSockets.size(); i++)
278          {
279            if ( networkSockets[i] != NULL )
280            {
[6634]281              PRINTF(5)("write %d bytes to socket %d\n", dataLength, i);
[6139]282              networkSockets[i]->writePacket(downBuffer, dataLength);
283            }
284          }
285        }
286
287      } while( reciever!=0 );
288    }
[5996]289  }
[5741]290
291  /* UPSTREAM */
[5809]292
[6139]293  for ( int i = 0; i<networkSockets.size(); i++)
[5802]294  {
[6139]295    if ( networkSockets[i] )
[5810]296    {
[6139]297      do {
298        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
[5730]299
[6139]300        if ( dataLength<=0 )
301          continue;
302
303        header = networkProtocol->extractHeader(upBuffer, dataLength);
304        dataLength -= sizeof(header);
305
[6498]306        PRINTF(5)("read %d bytes from socket uniqueID = %d\n", dataLength, header.synchronizeableID);
[6341]307
[6139]308        if ( dataLength != header.length )
309        {
310          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
311          continue;
312        }
313
314        if ( header.synchronizeableID == 0 )
315        {
316          header.synchronizeableID = i;
317        }
318
319        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
320        {
321          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
[6341]322          {
323            if ( (*it)->writeBytes(upBuffer+sizeof(header), dataLength, i) != header.length )
324            {
[6634]325              PRINTF(1)("%s did not read all the data id = %d!\n", (*it)->getClassName(), (*it)->getUniqueID());
[6341]326              break;
327            }
328            continue;
329          }
[6139]330        }
331
332      } while ( dataLength>0 );
[5810]333    }
334  }
[6139]335}
336
337void NetworkStream::updateConnectionList( )
338{
339  //check for new connections
340
341  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
342
343  if ( tempNetworkSocket )
[5810]344  {
[6139]345    int clientId;
346    if ( freeSocketSlots.size() >0 )
[5810]347    {
[6139]348      clientId = freeSocketSlots.back();
349      freeSocketSlots.pop_back();
350      networkSockets[clientId] = tempNetworkSocket;
[6341]351      handshakes[clientId] = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
[6139]352      handshakes[clientId]->setUniqueID(clientId);
353    } else
354    {
355      clientId = networkSockets.size();
356      networkSockets.push_back(tempNetworkSocket);
[6341]357      Handshake* tHs = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
[6139]358      tHs->setUniqueID(clientId);
359      handshakes.push_back(tHs);
360    }
[5730]361
[6139]362    if ( clientId > this->maxConnections )
363    {
364      handshakes[clientId]->doReject();
365      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
[5810]366    }
[6139]367    else
368
369    PRINTF(0)("New Client: %d\n", clientId);
370
[6661]371    //this->connectSynchronizeable(*handshakes[clientId]);
[5802]372  }
[5800]373
[5809]374
[6139]375  //check if connections are ok else remove them
376  for ( int i = 1; i<networkSockets.size(); i++)
377  {
378    if ( networkSockets[i] && !networkSockets[i]->isOk() )
379    {
380      //TODO: tell EntityManager that this player left the game
381      PRINTF(0)("Client is gone: %d\n", i);
382
383      //delete networkSockets[i];
384      networkSockets[i]->disconnectServer();
385      networkSockets[i]->destroy();
386      networkSockets[i] = NULL;
[6498]387
[6139]388      if ( handshakes[i] )
389        delete handshakes[i];
390      handshakes[i] = NULL;
391
392      if ( i == networkSockets.size()-1 )
393      {
394        networkSockets.pop_back();
395        handshakes.pop_back();
396      }
397      else
398      {
399        freeSocketSlots.push_back(i);
400      }
401    }
402  }
403
404
[5604]405}
[6139]406
407void NetworkStream::setMaxConnections( int n )
408{
409  if ( !this->isServer() )
410  {
411    PRINTF(1)("Cannot set maxConnections because I am no server.\n");
412  }
413  if ( this->networkSockets.size() > 1 )
414  {
415    PRINTF(1)("Cannot set maxConnections because there are already %d connections.\n", this->networkSockets.size());
416    return;
417  }
[6341]418
419  if ( n > MAX_CONNECTIONS )
420  {
421    PRINTF(1)("Cannot set maxConnectiosn to %d because of hardcoded limit %d\n", n, MAX_CONNECTIONS);
422    return;
423  }
424
[6139]425  this->maxConnections = n;
[6341]426  this->networkGameManager->setUniqueID( n+2 );
[6139]427}
428
429
[6658]430
431void NetworkStream::debug()
432{
[6660]433  if( this->isServer())
434    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
435  else
436    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
[6658]437
[6660]438  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
[6658]439  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
440  {
[6673]441    if( (*it)->beSynchronized() == true)
[6660]442      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
443               (*it)->getUniqueID(), (*it)->beSynchronized());
[6658]444  }
445  PRINT(0)(" Maximal Connections: %i\n", this->maxConnections);
446
447}
448
449
[6672]450int NetworkStream::getSyncCount()
451{
452  int n = 0;
453  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
454    if( (*it)->beSynchronized() == true)
455      ++n;
[6658]456
[6672]457  //return synchronizeables.size();
458  return n;
459}
[6658]460
461
462
463
464
465
Note: See TracBrowser for help on using the repository browser.