Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

redirection flag added, proxy settings as a way to get/save the server settings

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