Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7792 was 7792, checked in by rennerc, 18 years ago

fixed bug

File size: 17.0 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"
[7565]25#include "udp_socket.h"
26#include "udp_server_socket.h"
[5647]27#include "connection_monitor.h"
28#include "synchronizeable.h"
[6341]29#include "network_game_manager.h"
[6959]30#include "shared_network_data.h"
[7671]31#include "message_manager.h"
[6341]32
[7748]33#include "network_log.h"
34
35
[7565]36#include "lib/util/loading/factory.h"
37
[5649]38#include "debug.h"
[6139]39#include "class_list.h"
[6144]40#include <algorithm>
[5647]41
[5566]42/* include your own header */
43#include "network_stream.h"
44
[5595]45/* probably unnecessary */
[5594]46using namespace std;
47
[5595]48
[5747]49#define PACKAGE_SIZE  256
[5647]50
[5747]51
[5800]52NetworkStream::NetworkStream()
[5996]53    : DataStream()
[5647]54{
55  this->init();
[5648]56  /* initialize the references */
[5996]57  this->type = NET_CLIENT;
[5647]58}
59
[6695]60
[7540]61NetworkStream::NetworkStream( std::string host, int port )
[5996]62{
[6139]63  this->type = NET_CLIENT;
[5996]64  this->init();
[7565]65  this->peers[0].socket = new UdpSocket( host, port );
[7631]66  this->peers[0].userId = 0;
67  this->peers[0].isServer = true;
[7767]68  this->peers[0].connectionMonitor = new ConnectionMonitor( 0 );
[5996]69}
70
71
[7565]72NetworkStream::NetworkStream( int port )
[5647]73{
[6139]74  this->type = NET_SERVER;
[5647]75  this->init();
[7565]76  this->serverSocket = new UdpServerSocket(port);
[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;
[7565]89  currentState = 0;
[5594]90}
91
[5647]92
[5566]93NetworkStream::~NetworkStream()
[5598]94{
[6139]95  if ( this->serverSocket )
96  {
97    serverSocket->close();
98    delete serverSocket;
99  }
[5723]100
[7565]101  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
[6139]102  {
[7565]103    if ( i->second.socket )
[6139]104    {
[7565]105      i->second.socket->disconnectServer();
106      delete i->second.socket;
107      i->second.socket = NULL;
[6139]108    }
[7565]109   
110    if ( i->second.handshake )
[6139]111    {
[7565]112      delete i->second.handshake;
113      i->second.handshake = NULL;
[6139]114    }
115  }
[7565]116 
117  if ( serverSocket )
118  {
119    delete serverSocket;
120    serverSocket = NULL;
121  }
[5805]122
[5598]123}
124
[5996]125
[6695]126void NetworkStream::createNetworkGameManager()
127{
128  this->networkGameManager = NetworkGameManager::getInstance();
129  // setUniqueID( maxCon+2 ) because we need one id for every handshake
130  // and one for handshake to reject client maxCon+1
[7684]131  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
[7681]132  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
[6695]133}
134
135
136void NetworkStream::startHandshake()
137{
138  Handshake* hs = new Handshake(false);
139  hs->setUniqueID( 0 );
[7565]140  assert( peers[0].handshake == NULL );
141  peers[0].handshake = hs;
[7575]142//   peers[0].handshake->setSynchronized( true );
[6695]143  //this->connectSynchronizeable(*hs);
[7591]144  //this->connectSynchronizeable(*hs);
[7575]145  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getName());
[6695]146}
147
148
[5996]149void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
150{
[6139]151  this->synchronizeables.push_back(&sync);
152  sync.setNetworkStream( this );
153
[7565]154  this->bActive = true;
[5996]155}
156
[6695]157
[6139]158void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
159{
[6144]160  // removing the Synchronizeable from the List.
161  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
162  if (disconnectSynchro != this->synchronizeables.end())
163    this->synchronizeables.erase(disconnectSynchro);
[7602]164 
[7767]165  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
[6139]166}
167
168
[5604]169void NetworkStream::processData()
170{
[7565]171  currentState++;
172 
[6139]173  if ( this->type == NET_SERVER )
[7571]174  {
175    if ( serverSocket )
176      serverSocket->update();
177   
[6139]178    this->updateConnectionList();
[7571]179  }
[6139]180  else
181  {
[7565]182    if ( peers[0].socket && !peers[0].socket->isOk() )
[6139]183    {
184      PRINTF(1)("lost connection to server\n");
[5741]185
[7565]186      peers[0].socket->disconnectServer();
187      delete peers[0].socket;
188      peers[0].socket = NULL;
[6498]189
[7565]190      if ( peers[0].handshake )
191        delete peers[0].handshake;
192      peers[0].handshake = NULL;
[6139]193    }
194  }
195
[7767]196  cleanUpOldSyncList();
[7575]197  handleHandshakes();
[7792]198 
199  handleDownstream();
[7701]200  handleUpstream();
[6341]201
[6139]202}
203
204void NetworkStream::updateConnectionList( )
205{
206  //check for new connections
207
208  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
209
210  if ( tempNetworkSocket )
[5810]211  {
[6139]212    int clientId;
213    if ( freeSocketSlots.size() >0 )
[5810]214    {
[6139]215      clientId = freeSocketSlots.back();
216      freeSocketSlots.pop_back();
[7565]217      peers[clientId].socket = tempNetworkSocket;
[7681]218      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID() );
[7767]219      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
[7565]220      peers[clientId].handshake->setUniqueID(clientId);
221      peers[clientId].userId = clientId;
[7631]222      peers[clientId].isServer = false;
[6139]223    } else
224    {
[7575]225      clientId = 1;
[7565]226     
227      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
228        if ( it->first >= clientId )
229          clientId = it->first + 1;
230     
231      peers[clientId].socket = tempNetworkSocket;
[7681]232      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
[7565]233      peers[clientId].handshake->setUniqueID(clientId);
[7767]234      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
[7565]235      peers[clientId].userId = clientId;
[7631]236      peers[clientId].isServer = false;
[7613]237     
238      PRINTF(0)("num sync: %d\n", synchronizeables.size());
[6139]239    }
[5730]240
[7575]241    if ( clientId > MAX_CONNECTIONS )
[6139]242    {
[7565]243      peers[clientId].handshake->doReject( "too many connections" );
[6139]244      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
[5810]245    }
[6139]246    else
247
248    PRINTF(0)("New Client: %d\n", clientId);
249
[6695]250    //this->connectSynchronizeable(*handshakes[clientId]);
[5802]251  }
[5800]252
[6139]253  //check if connections are ok else remove them
[7565]254  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
[6139]255  {
[7767]256    if ( 
[7792]257          it->second.socket &&
258          ( 
259            !it->second.socket->isOk()  ||
260            it->second.connectionMonitor->hasTimedOut()
261          )
[7767]262       )
[6139]263    {
[7565]264      PRINTF(0)("Client is gone: %d\n", it->second.userId);
[6139]265
[7565]266      it->second.socket->disconnectServer();
267      delete it->second.socket;
268      it->second.socket = NULL;
[6498]269
[7565]270      if ( it->second.handshake )
271        delete it->second.handshake;
272      it->second.handshake = NULL;
[7631]273     
274      for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )
275      {
276        (*it2)->cleanUpUser( it->second.userId );
277      }
[6139]278
[7565]279      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
[6737]280
[7565]281      freeSocketSlots.push_back( it->second.userId );
282
[6139]283    }
284  }
285
286
[5604]287}
[6139]288
[6695]289void NetworkStream::debug()
290{
291  if( this->isServer())
292    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
293  else
294    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
295
296  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
297  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
298  {
299    if( (*it)->beSynchronized() == true)
300      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
301               (*it)->getUniqueID(), (*it)->beSynchronized());
302  }
[7575]303  PRINT(0)(" Maximal Connections: %i\n", MAX_CONNECTIONS );
[6695]304
305}
306
307
308int NetworkStream::getSyncCount()
309{
310  int n = 0;
311  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
312    if( (*it)->beSynchronized() == true)
313      ++n;
314
315  //return synchronizeables.size();
316  return n;
317}
318
[7565]319/**
320 * check if handshakes completed
321 */
322void NetworkStream::handleHandshakes( )
323{
324  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
325  {
326    if ( it->second.handshake )
327    {
328      if ( it->second.handshake->completed() )
329      {
330        if ( it->second.handshake->ok() )
331        {
332          if ( type != NET_SERVER )
333          {
334            SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
335            myHostId = SharedNetworkData::getInstance()->getHostID();
[6695]336
[7565]337            this->networkGameManager = NetworkGameManager::getInstance();
338            this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
[7681]339            MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
[7773]340          }
[7792]341          else
342            handleNewClient( it->second.userId );
[6695]343
[7778]344          PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
[6695]345
[7565]346          delete it->second.handshake;
347          it->second.handshake = NULL;
[7792]348
[7565]349        }
350        else
351        {
[7778]352          PRINT(1)("handshake failed!\n");
[7565]353          it->second.socket->disconnectServer();
354        }
355      }
356    }
357  }
358}
[6695]359
[7565]360/**
361 * handle upstream network traffic
362 */
363void NetworkStream::handleUpstream( )
364{
365  byte buf[UDP_PACKET_SIZE];
366  int offset;
367  int n;
368 
369  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
370  {
371    offset = INTSIZE; //make already space for length
372   
[7575]373    if ( !peer->second.socket )
[7565]374      continue;
375   
376    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
377    assert( n == INTSIZE );
378    offset += n;
379   
380    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
381    assert( n == INTSIZE );
382    offset += n;
383   
384    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
385    assert( n == INTSIZE );
386    offset += n;
387   
388    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
389    {
390      Synchronizeable & sync = **it;
[7591]391     
[7575]392      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
393        continue;
394
395      //if handshake not finished only sync handshake
396      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
397        continue;
[7591]398     
399      if ( isServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
400        continue;
[7614]401     
402      //do not sync null parent
403      if ( sync.getLeafClassID() == CL_NULL_PARENT )
404        continue;
[7575]405
[7565]406      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
407     
[7575]408      //server fakes uniqueid=0 for handshake
409      if ( this->isServer() && sync.getUniqueID() < MAX_CONNECTIONS - 1 )
410        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
411      else
412        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
[7565]413      assert( n == INTSIZE );
414      offset += n;
415     
[7602]416      //make space for size
417      offset += INTSIZE;
[7614]418
[7731]419      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
[7602]420      offset += n;
421     
[7614]422      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
[7565]423    }
424   
425    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
426   
427    assert( peer->second.socket->writePacket( buf, offset ) );
[7767]428   
[7778]429    peer->second.connectionMonitor->processUnzippedOutgoingPacket( buf, offset, currentState );
[7777]430   
[7752]431    NETPRINTF(n)("send packet: %d userId = %d\n", offset, peer->second.userId);
[7565]432  }
433}
434
435/**
436 * handle downstream network traffic
437 */
438void NetworkStream::handleDownstream( )
439{
440  byte buf[UDP_PACKET_SIZE];
441  int offset = 0;
442 
443  int length = 0;
444  int packetLength = 0;
445  int uniqueId = 0;
446  int state = 0;
447  int ackedState = 0;
448  int fromState = 0;
[7602]449  int syncDataLength = 0;
[7565]450 
451  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
452  {
[7614]453   
[7575]454    if ( !peer->second.socket )
455      continue;
456
[7681]457    while ( 0 < (packetLength = peer->second.socket->readPacket( buf, UDP_PACKET_SIZE )) )
[7659]458    {
[7575]459
[7659]460      if ( packetLength < 4*INTSIZE )
461      {
462        if ( packetLength != 0 )
463          PRINTF(1)("got too small packet: %d\n", packetLength);
464        continue;
465      }
[7565]466   
[7659]467      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
468      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
469      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
470      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
[7752]471      NETPRINTF(n)("ackedstate: %d\n", ackedState);
[7659]472      offset = 4*INTSIZE;
[7575]473
[7752]474      NETPRINTF(n)("got packet: %d, %d\n", length, packetLength);
[7565]475   
476    //if this is an old state drop it
[7659]477      if ( state <= peer->second.lastRecvedState )
478        continue;
[7565]479   
[7659]480      if ( packetLength != length )
481      {
482        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
483        peer->second.socket->disconnectServer();
484        continue;
485      }
[7731]486     
[7659]487      while ( offset < length )
488      {
489        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
490        offset += INTSIZE;
[7565]491     
[7659]492        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
493        offset += INTSIZE;
[7602]494     
[7659]495        Synchronizeable * sync = NULL;
[7731]496       
[7659]497        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
498        { 
[7575]499        //                                        client thinks his handshake has id 0!!!!!
[7659]500          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
501          {
502            sync = *it;
503            break;
504          }
[7565]505        }
[7731]506       
[7659]507        if ( sync == NULL )
[7602]508        {
[7792]509          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
[7659]510          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
511          {
512            offset += syncDataLength;
513            continue;
514          }
[7731]515
[7767]516          if ( !peers[peer->second.userId].isServer )
517          {
518            offset += syncDataLength;
519            continue;
520          }
521         
[7659]522          int leafClassId;
523          if ( INTSIZE > length - offset )
524          {
525            offset += syncDataLength;
526            continue;
527          }
[7731]528
[7659]529          Converter::byteArrayToInt( buf + offset, &leafClassId );
[7792]530         
531          assert( leafClassId != 0 );
[7565]532       
[7792]533          BaseObject * b = NULL;
[7659]534          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
535          /* Exception 1: NullParent */
[7792]536          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
[7659]537          {
538            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
539            offset += syncDataLength;
540            continue;
541          }
542          else
543            b = Factory::fabricate( (ClassID)leafClassId );
[7565]544
[7659]545          if ( !b )
546          {
547            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
548            offset += syncDataLength;
549            continue;
550          }
[7731]551
[7659]552          if ( b->isA(CL_SYNCHRONIZEABLE) )
553          {
554            sync = dynamic_cast<Synchronizeable*>(b);
555            sync->setUniqueID( uniqueId );
556            sync->setSynchronized(true);
[7565]557 
[7659]558            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
559          }
560          else
561          {
562            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
563            delete b;
564            offset += syncDataLength;
565            continue;
566          }
[7565]567        }
[7659]568
[7731]569        offset += sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState ); 
[7565]570      }
[7731]571     
[7659]572      if ( offset != length )
573      {
[7731]574        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
[7659]575        peer->second.socket->disconnectServer();
576      }
[7731]577     
[7778]578      peer->second.connectionMonitor->processUnzippedIncomingPacket( buf, offset, currentState, ackedState );
[7659]579   
580      peer->second.lastAckedState = ackedState;
[7792]581     
[7731]582      peer->second.lastRecvedState = state;
583     
[7565]584    }
[7659]585 
[7565]586  }
[7614]587 
[7565]588}
589
[7671]590/**
591 * is executed when a handshake has finished
592 * @todo create playable for new user
593 */
594void NetworkStream::handleNewClient( int userId )
595{
596  MessageManager::getInstance()->initUser( userId );
[7693]597 
598  networkGameManager->signalNewPlayer( userId );
[7671]599}
[7565]600
[7767]601/**
602 * removes old items from oldSynchronizeables
603 */
604void NetworkStream::cleanUpOldSyncList( )
605{
606  int now = SDL_GetTicks();
607 
608  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
609  {
610    if ( it->second < now - 10*1000 )
611    {
612      std::map<int,int>::iterator delIt = it;
613      it++;
614      oldSynchronizeables.erase( delIt );
615      continue;
616    }
617    it++;
618  }
619}
[7565]620
621
622
623
[7671]624
[7767]625
Note: See TracBrowser for help on using the repository browser.