Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

node type now saved

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