Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

saver state handling and first proxy clause

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