Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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