Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

other unique id offset

File size: 28.4 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: Christoph Renner rennerc@ee.ethz.ch
13   co-programmer:   Patrick Boenzli  boenzlip@orxonox.ethz.ch
14
15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
16     July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
17*/
18
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 "monitor/connection_monitor.h"
28#include "monitor/network_monitor.h"
29#include "synchronizeable.h"
30#include "ip.h"
31#include "network_game_manager.h"
32#include "shared_network_data.h"
33#include "message_manager.h"
34#include "preferences.h"
35#include "zip.h"
36
37#include "src/lib/util/loading/resource_manager.h"
38
39#include "network_log.h"
40
41#include "player_stats.h"
42
43#include "lib/util/loading/factory.h"
44
45#include "debug.h"
46#include "class_list.h"
47#include <algorithm>
48
49
50#include "network_stream.h"
51
52
53
54
55
56#define PACKAGE_SIZE  256
57
58
59/**
60 * empty constructor
61 */
62NetworkStream::NetworkStream()
63    : DataStream()
64{
65  this->init();
66  /* initialize the references */
67  this->pInfo->nodeType = NET_CLIENT;
68}
69
70
71/**
72 * start as a client, connect to a server
73 *  @param host: host name (address)
74 *  @param port: port number
75 */
76NetworkStream::NetworkStream( std::string host, int port )
77{
78  this->init();
79  // init the peers[0] the server to ceonnect to
80  this->peers[0].socket = new UdpSocket( host, port );
81  this->peers[0].userId = 0;
82  this->peers[0].nodeType = NET_MASTER_SERVER;
83  this->peers[0].connectionMonitor = new ConnectionMonitor( 0 );
84  this->peers[0].ip = this->peers[0].socket->getRemoteAddress();
85  // and set also the localhost
86  this->pInfo->nodeType = NET_CLIENT;
87  // get the local ip address
88  IPaddress ip;
89  SDLNet_ResolveHost( &ip, NULL, port );
90  this->pInfo->ip = ip;
91}
92
93
94/**
95 * start as a server
96 *  @param port: at this port
97 */
98NetworkStream::NetworkStream( int port )
99{
100  this->init();
101  this->serverSocket = new UdpServerSocket(port);
102  this->pInfo->nodeType = NET_MASTER_SERVER;
103  // get the local ip address
104  IPaddress ip;
105  SDLNet_ResolveHost( &ip, NULL, port );
106  this->pInfo->ip = ip;
107}
108
109
110/**
111 * generic init functions
112 */
113void NetworkStream::init()
114{
115  /* set the class id for the base object */
116  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
117  this->serverSocket = NULL;
118  this->networkGameManager = NULL;
119  this->networkMonitor = NULL;
120
121  this->pInfo = new PeerInfo();
122  this->pInfo->userId = 0;
123  this->pInfo->lastAckedState = 0;
124  this->pInfo->lastRecvedState = 0;
125
126
127  this->currentState = 0;
128
129  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
130
131  assert( Zip::getInstance()->loadDictionary( "testdict" ) >= 0 );
132  this->dictClient = Zip::getInstance()->loadDictionary( "dict2pl_client" );
133  assert( this->dictClient >= 0 );
134  this->dictServer = Zip::getInstance()->loadDictionary( "dict2p_server" );
135  assert( this->dictServer >= 0 );
136}
137
138
139/**
140 * deconstructor
141 */
142NetworkStream::~NetworkStream()
143{
144  if ( this->serverSocket )
145  {
146    serverSocket->close();
147    delete serverSocket;
148    serverSocket = NULL;
149  }
150  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
151  {
152    if ( i->second.socket )
153    {
154      i->second.socket->disconnectServer();
155      delete i->second.socket;
156      i->second.socket = NULL;
157    }
158
159    if ( i->second.handshake )
160    {
161      delete i->second.handshake;
162      i->second.handshake = NULL;
163    }
164
165    if ( i->second.connectionMonitor )
166    {
167      delete i->second.connectionMonitor;
168      i->second.connectionMonitor = NULL;
169    }
170  }
171  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
172    (*it)->setNetworkStream( NULL );
173
174  if( this->pInfo)
175    delete this->pInfo;
176
177  if( this->networkMonitor)
178    delete this->networkMonitor;
179}
180
181
182/**
183 * creates a new instance of the network game manager
184 */
185void NetworkStream::createNetworkGameManager()
186{
187  this->networkGameManager = NetworkGameManager::getInstance();
188  // setUniqueID( maxCon+2 ) because we need one id for every handshake
189  // and one for handshake to reject client maxCon+1
190  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
191  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
192}
193
194
195/**
196 * starts the network handshake
197 * handsakes are always initialized from the client side first. this starts the handshake and therefore is only
198 * executed as client
199 */
200void NetworkStream::startHandshake()
201{
202  Handshake* hs = new Handshake(this->pInfo->nodeType);
203  hs->setUniqueID( 0 );
204  assert( peers[0].handshake == NULL );
205  peers[0].handshake = hs;
206
207  // set the preferred nick name
208  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
209
210  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getCName());
211}
212
213
214/**
215 * this functions connects a synchronizeable to the networkstream, therefore synchronizeing
216 * it all over the network and creating it on the other platforms (if and only if it is a
217 * server
218 */
219void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
220{
221  this->synchronizeables.push_back(&sync);
222  sync.setNetworkStream( this );
223
224//   this->bActive = true;
225}
226
227
228/**
229 * removes the synchronizeable from the list of synchronized entities
230 */
231void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
232{
233  // removing the Synchronizeable from the List.
234  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
235  if (disconnectSynchro != this->synchronizeables.end())
236    this->synchronizeables.erase(disconnectSynchro);
237
238  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
239}
240
241
242/**
243 * this is called to process data from the network socket to the synchronizeable and vice versa
244 */
245void NetworkStream::processData()
246{
247  // create the network monitor after all the init work and before there is any connection handlings
248  if( this->networkMonitor == NULL)
249    this->networkMonitor = new NetworkMonitor(this);
250
251
252  int tick = SDL_GetTicks();
253
254  this->currentState++;
255  // there was a wrap around
256  if( this->currentState < 0)
257  {
258    PRINTF(1)("A wrap around in the state variable as occured. The server was running so long? Pls restart server or write a mail to the supporters!\n");
259  }
260
261  if ( this->pInfo->nodeType == NET_MASTER_SERVER )
262  {
263    // execute everytthing the master server shoudl do
264    if ( serverSocket )
265      serverSocket->update();
266
267    this->updateConnectionList();
268  }
269  else if( this->pInfo->nodeType == NET_PROXY_SERVER_ACTIVE)
270  {
271    // execute everything the proxy server should do
272  }
273  else
274  {
275    // check if the connection is ok else terminate and remove
276    if ( peers[0].socket && ( !peers[0].socket->isOk() || peers[0].connectionMonitor->hasTimedOut() ) )
277    {
278      PRINTF(1)("lost connection to server\n");
279
280      peers[0].socket->disconnectServer();
281      delete peers[0].socket;
282      peers[0].socket = NULL;
283
284      if ( peers[0].handshake )
285        delete peers[0].handshake;
286      peers[0].handshake = NULL;
287
288      if ( peers[0].connectionMonitor )
289        delete peers[0].connectionMonitor;
290      peers[0].connectionMonitor = NULL;
291    }
292  }
293
294  cleanUpOldSyncList();
295  handleHandshakes();
296
297  // update the network monitor
298  this->networkMonitor->process();
299
300  // order of up/downstream is important!!!!
301  // don't change it
302  handleDownstream( tick );
303  handleUpstream( tick );
304}
305
306
307/**
308 * if we are a NET_MASTER_SERVER or NET_PROXY_SERVER_ACTIVE update the connection list to accept new
309 * connections (clients) also start the handsake for the new clients
310 */
311void NetworkStream::updateConnectionList( )
312{
313  //check for new connections
314
315  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
316
317  // we got new network node
318  if ( tempNetworkSocket )
319  {
320    int clientId;
321    // if there is a list of free client id slots, take these
322    if ( freeSocketSlots.size() > 0 )
323    {
324      clientId = freeSocketSlots.back();
325      freeSocketSlots.pop_back();
326    }
327    else
328    {
329      clientId = 1;
330
331      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
332        if ( it->first >= clientId )
333          clientId = it->first + 1;
334    }
335
336    peers[clientId].socket = tempNetworkSocket;
337    // create new handshake and init its variables
338    peers[clientId].handshake = new Handshake(this->pInfo->nodeType, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID() );
339    peers[clientId].handshake->setUniqueID(clientId);
340
341    peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
342    peers[clientId].userId = clientId;
343
344    PRINTF(0)("num sync: %d\n", synchronizeables.size());
345
346    // get the proxy server informations and write them to the handshake, if any (proxy)
347    assert( this->networkMonitor != NULL);
348    PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
349    if( pi != NULL)
350    {
351      peers[clientId].handshake->setProxy1Address( pi->ip);
352    }
353    pi = this->networkMonitor->getSecondChoiceProxy();
354    if( pi != NULL)
355      peers[clientId].handshake->setProxy2Address( pi->ip);
356
357    // check if the connecting client should reconnect to a proxy server
358    peers[clientId].handshake->setRedirect(this->networkMonitor->isReconnectNextClient());
359
360    // the connecting node of course is a client
361    peers[clientId].nodeType = NET_CLIENT;
362    peers[clientId].ip = peers[clientId].socket->getRemoteAddress();
363
364
365    // check if there are too many clients connected (DEPRECATED: new: the masterserver sends a list of proxy servers)
366//     if ( clientId > SharedNetworkData::getInstance()->getMaxPlayer() )
367//     {
368// //       peers[clientId].handshake->setRedirect(true);
369// //
370// //       peers[clientId].handshake->doReject( "too many connections" );
371//       PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
372//     }
373//     else
374//     {
375//       PRINTF(0)("New Client: %d\n", clientId);
376//     }
377    PRINTF(0)("New Client: %d\n", clientId);
378
379
380  }
381
382
383
384  //check if connections are ok else remove them
385  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
386  {
387    if (
388          it->second.socket &&
389          (
390            !it->second.socket->isOk()  ||
391            it->second.connectionMonitor->hasTimedOut()
392          )
393       )
394    {
395      std::string reason = "disconnected";
396      if ( it->second.connectionMonitor->hasTimedOut() )
397        reason = "timeout";
398      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
399
400
401      // clean up the network data
402      it->second.socket->disconnectServer();
403      delete it->second.socket;
404      it->second.socket = NULL;
405
406      // remove the old connectin monitor
407      if ( it->second.connectionMonitor )
408        delete it->second.connectionMonitor;
409      it->second.connectionMonitor = NULL;
410
411      // remove the handshake
412      if ( it->second.handshake )
413        delete it->second.handshake;
414      it->second.handshake = NULL;
415
416      // and cleanup the user infos
417      for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )
418      {
419        (*it2)->cleanUpUser( it->second.userId );
420      }
421
422      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
423
424      freeSocketSlots.push_back( it->second.userId );
425
426      PeerList::iterator delit = it;
427      it++;
428
429      peers.erase( delit );
430
431      continue;
432    }
433
434    it++;
435  }
436
437
438}
439
440
441void NetworkStream::debug()
442{
443  if( this->isMasterServer())
444    PRINT(0)(" Host ist Server with ID: %i\n", this->pInfo->userId);
445  else
446    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
447
448  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
449  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
450  {
451    if( (*it)->beSynchronized() == true)
452      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassCName(), (*it)->getCName(),
453               (*it)->getUniqueID(), (*it)->beSynchronized());
454  }
455  PRINT(0)(" Maximal Connections: %i\n", SharedNetworkData::getInstance()->getMaxPlayer() );
456
457}
458
459
460/**
461 * @returns the number of synchronizeables registered to this stream
462 */
463int NetworkStream::getSyncCount()
464{
465  int n = 0;
466  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
467    if( (*it)->beSynchronized() == true)
468      ++n;
469
470  //return synchronizeables.size();
471  return n;
472}
473
474
475/**
476 * check if handshakes completed. if so create the network game manager else remove it again
477 */
478void NetworkStream::handleHandshakes( )
479{
480  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
481  {
482    if ( it->second.handshake )
483    {
484      // handshake finished
485      if ( it->second.handshake->completed() )
486      {
487        //handshake is correct
488        if ( it->second.handshake->ok() )
489        {
490          // the server gave it free for deletion
491          if ( !it->second.handshake->allowDel() )
492          {
493
494            if ( this->pInfo->nodeType == NET_CLIENT )
495            {
496
497              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
498              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
499
500              it->second.nodeType = it->second.handshake->getRemoteNodeType();
501              it->second.ip = it->second.socket->getRemoteAddress();
502              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
503              this->networkMonitor->addNode(&it->second);
504              // get proxy 1 address and add it
505              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
506              // get proxy 2 address and add it
507              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
508
509              // now check if the server accepted the connection
510              if( it->second.handshake->redirect())
511                this->handleReconnect( it->second.userId);
512
513              // create the new network game manager and init it
514              this->networkGameManager = NetworkGameManager::getInstance();
515              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
516              // init the new message manager
517              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
518            }
519
520
521            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
522            it->second.handshake->del();
523          }
524          else
525          {
526            // handshake finished registring new player
527            if ( it->second.handshake->canDel() )
528            {
529              if ( this->pInfo->nodeType == NET_MASTER_SERVER )
530              {
531                it->second.nodeType = it->second.handshake->getRemoteNodeType();
532                it->second.ip = it->second.socket->getRemoteAddress();
533
534                this->networkMonitor->addNode(&it->second);
535
536                this->handleNewClient( it->second.userId );
537
538                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
539                {
540                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
541                }
542              }
543
544              PRINT(0)("handshake finished delete it\n");
545              delete it->second.handshake;
546              it->second.handshake = NULL;
547            }
548          }
549
550        }
551        else
552        {
553          PRINT(1)("handshake failed!\n");
554          it->second.socket->disconnectServer();
555        }
556      }
557    }
558  }
559}
560
561
562/**
563 * this functions handles a reconnect event received from the a NET_MASTER_SERVER or NET_PROXY_SERVER
564 */
565void NetworkStream::handleReconnect(int userId)
566{
567  PRINTF(0)("===============================================\n");
568  PRINTF(0)("Client is redirected to the other proxy servers\n");
569  PRINTF(0)("===============================================\n");
570
571  return;
572
573  PeerInfo* pInfo = &this->peers[userId];
574
575  // reject the server
576  pInfo->handshake->doReject( "redirected to different server");
577
578  // flush the old synchronization states, since the numbering could be completely different
579  pInfo->lastAckedState = 0;
580  pInfo->lastRecvedState = 0;
581  // not sure if this works as expected
582  if( pInfo->handshake)
583    delete pInfo->handshake;
584
585  // disconnect from the current server and reconnect to proxy server
586  pInfo->socket->reconnectToServer( pInfo->handshake->getProxy1Address().ipString(), pInfo->handshake->getProxy1Address().port());
587
588  // and restart the handshake
589  this->startHandshake();
590}
591
592
593/**
594 * handle upstream network traffic
595 */
596void NetworkStream::handleUpstream( int tick )
597{
598  int offset;
599  int n;
600
601  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
602  {
603    offset = INTSIZE; // reserve enough space for the packet length
604
605    // continue with the next peer if this peer has no socket assigned (therefore no network)
606    if ( !peer->second.socket )
607      continue;
608
609    // header informations: current state
610    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
611    assert( n == INTSIZE );
612    offset += n;
613
614    // header informations: last acked state
615    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
616    assert( n == INTSIZE );
617    offset += n;
618
619    // header informations: last recved state
620    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
621    assert( n == INTSIZE );
622    offset += n;
623
624    // now write all synchronizeables in the packet
625    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
626    {
627      int oldOffset = offset;
628      Synchronizeable & sync = **it;
629
630      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
631      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
632        continue;
633
634      // if handshake not finished only sync handshake
635      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
636        continue;
637
638      // if we are a server and this is not our handshake
639      if ( isMasterServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
640        continue;
641
642      /* list of synchronizeables that will never be synchronized over the network: */
643      // do not sync null parent
644      if ( sync.getLeafClassID() == CL_NULL_PARENT )
645        continue;
646
647      assert( sync.getLeafClassID() != 0);
648
649      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
650
651      // server fakes uniqueid == 0 for handshake
652      if ( this->isMasterServer() && sync.getUniqueID() < SharedNetworkData::getInstance()->getMaxPlayer() - 1 )
653        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
654      else
655        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
656
657      assert( n == INTSIZE );
658      offset += n;
659
660      // make space for size
661      offset += INTSIZE;
662
663      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
664      offset += n;
665
666      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
667
668      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
669      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
670      bool allZero = true;
671      for ( int i = 0; i < n; i++ )
672      {
673         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
674           allZero = false;
675      }
676      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
677      // data that hast not changed
678      if ( allZero )
679      {
680        offset = oldOffset;
681      }
682    } // all synchronizeables written
683
684
685
686    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
687    {
688      Synchronizeable & sync = **it;
689
690      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
691        continue;
692
693      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
694    }
695
696
697    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
698
699    // now compress the data with the zip library
700    int compLength = 0;
701    if ( this->isMasterServer() )
702      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
703    else
704      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
705
706    if ( compLength <= 0 )
707    {
708      PRINTF(1)("compression failed!\n");
709      continue;
710    }
711
712    assert( peer->second.socket->writePacket( compBuf, compLength ) );
713
714    if ( this->remainingBytesToWriteToDict > 0 )
715      writeToNewDict( buf, offset, true );
716
717    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
718    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
719
720  }
721}
722
723/**
724 * handle downstream network traffic
725 */
726void NetworkStream::handleDownstream( int tick )
727{
728  int offset = 0;
729
730  int length = 0;
731  int packetLength = 0;
732  int compLength = 0;
733  int uniqueId = 0;
734  int state = 0;
735  int ackedState = 0;
736  int fromState = 0;
737  int syncDataLength = 0;
738
739  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
740  {
741
742    if ( !peer->second.socket )
743      continue;
744
745    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
746    {
747      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
748
749      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
750
751      if ( packetLength < 4*INTSIZE )
752      {
753        if ( packetLength != 0 )
754          PRINTF(1)("got too small packet: %d\n", packetLength);
755        continue;
756      }
757
758      if ( this->remainingBytesToWriteToDict > 0 )
759        writeToNewDict( buf, packetLength, false );
760
761      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
762      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
763      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
764      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
765      offset = 4*INTSIZE;
766
767      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
768
769
770      //if this is an old state drop it
771      if ( state <= peer->second.lastRecvedState )
772        continue;
773
774      if ( packetLength != length )
775      {
776        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
777        peer->second.socket->disconnectServer();
778        continue;
779      }
780
781      while ( offset + 2*INTSIZE < length )
782      {
783        assert( offset > 0 );
784        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
785        offset += INTSIZE;
786
787        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
788        offset += INTSIZE;
789
790        assert( syncDataLength > 0 );
791        assert( syncDataLength < 10000 );
792
793        Synchronizeable * sync = NULL;
794
795        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
796        {
797        //                                        client thinks his handshake has id 0!!!!!
798          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
799          {
800            sync = *it;
801            break;
802          }
803        }
804
805        if ( sync == NULL )
806        {
807          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
808          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
809          {
810            offset += syncDataLength;
811            continue;
812          }
813
814          if ( !peers[peer->second.userId].isMasterServer() )
815          {
816            offset += syncDataLength;
817            continue;
818          }
819
820          int leafClassId;
821          if ( INTSIZE > length - offset )
822          {
823            offset += syncDataLength;
824            continue;
825          }
826
827          Converter::byteArrayToInt( buf + offset, &leafClassId );
828
829          assert( leafClassId != 0 );
830
831          BaseObject * b = NULL;
832          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
833          /* Exception 1: NullParent */
834          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
835          {
836            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
837            offset += syncDataLength;
838            continue;
839          }
840          else
841            b = Factory::fabricate( (ClassID)leafClassId );
842
843          if ( !b )
844          {
845            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
846            offset += syncDataLength;
847            continue;
848          }
849
850          if ( b->isA(CL_SYNCHRONIZEABLE) )
851          {
852            sync = dynamic_cast<Synchronizeable*>(b);
853            sync->setUniqueID( uniqueId );
854            sync->setSynchronized(true);
855
856            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
857          }
858          else
859          {
860            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
861            delete b;
862            offset += syncDataLength;
863            continue;
864          }
865        }
866
867
868        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
869        offset += n;
870
871      }
872
873      if ( offset != length )
874      {
875        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
876        peer->second.socket->disconnectServer();
877      }
878
879
880      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
881      {
882        Synchronizeable & sync = **it;
883
884        if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
885          continue;
886
887        sync.handleRecvState( peer->second.userId, state, fromState );
888      }
889
890      assert( peer->second.lastAckedState <= ackedState );
891      peer->second.lastAckedState = ackedState;
892
893      assert( peer->second.lastRecvedState < state );
894      peer->second.lastRecvedState = state;
895
896    }
897
898  }
899
900}
901
902/**
903 * is executed when a handshake has finished
904 */
905void NetworkStream::handleNewClient( int userId )
906{
907  // init and assign the message manager
908  MessageManager::getInstance()->initUser( userId );
909  // do all game relevant stuff here
910  networkGameManager->signalNewPlayer( userId );
911
912  // register the new client at the network monitor
913//   this->networkMonitor->addClient();
914}
915
916
917/**
918 * removes old items from oldSynchronizeables
919 */
920void NetworkStream::cleanUpOldSyncList( )
921{
922  int now = SDL_GetTicks();
923
924  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
925  {
926    if ( it->second < now - 10*1000 )
927    {
928      std::map<int,int>::iterator delIt = it;
929      it++;
930      oldSynchronizeables.erase( delIt );
931      continue;
932    }
933    it++;
934  }
935}
936
937/**
938 * writes data to DATA/dicts/newdict
939 * @param data pointer to data
940 * @param length length
941 */
942void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
943{
944  if ( remainingBytesToWriteToDict <= 0 )
945    return;
946
947  if ( length > remainingBytesToWriteToDict )
948    length = remainingBytesToWriteToDict;
949
950  std::string fileName = ResourceManager::getInstance()->getDataDir();
951  fileName += "/dicts/newdict";
952
953  if ( upstream )
954    fileName += "_upstream";
955  else
956    fileName += "_downstream";
957
958  FILE * f = fopen( fileName.c_str(), "a" );
959
960  if ( !f )
961  {
962    PRINTF(2)("could not open %s\n", fileName.c_str());
963    remainingBytesToWriteToDict = 0;
964    return;
965  }
966
967  if ( fwrite( data, 1, length, f ) != length )
968  {
969    PRINTF(2)("could not write to file\n");
970    fclose( f );
971    return;
972  }
973
974  fclose( f );
975
976  remainingBytesToWriteToDict -= length;
977}
978
979
980
981
982
983
Note: See TracBrowser for help on using the repository browser.