Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fixed bug

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