Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

added some debug functions/output

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