Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/network_stream.cc

Last change on this file was 10114, checked in by patrick, 17 years ago

merged network back to trunk

File size: 40.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
[9656]13   co-programmer:   Patrick Boenzli  patrick@orxonox.ethz.ch
[9406]14
15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
[9656]16     July 2006: some code rearangement and integration of the proxy server mechanism (patrick@orxonox.ethz.ch)
[5566]17*/
18
19
20#define DEBUG_MODULE_NETWORK
21
[9656]22#include "proxy/proxy_control.h"
[5747]23
[5647]24#include "base_object.h"
[5731]25#include "network_protocol.h"
[7954]26#include "udp_socket.h"
27#include "udp_server_socket.h"
[9406]28#include "monitor/connection_monitor.h"
29#include "monitor/network_monitor.h"
[5647]30#include "synchronizeable.h"
[9406]31#include "ip.h"
[6341]32#include "network_game_manager.h"
[6959]33#include "shared_network_data.h"
[7954]34#include "message_manager.h"
[9869]35#include "parser/preferences/preferences.h"
[7954]36#include "zip.h"
[6341]37
[7954]38#include "network_log.h"
39
[9235]40#include "player_stats.h"
[7954]41
[9869]42#include "loading/factory.h"
43#include "loading/resource_manager.h"
[7954]44
[5649]45#include "debug.h"
[5647]46
[5566]47#include "network_stream.h"
48
[5594]49
[9406]50#include "converter.h"
[5595]51
[9406]52
[5747]53#define PACKAGE_SIZE  256
[5647]54
[9869]55ObjectListDefinition(NetworkStream);
[9406]56/**
57 * empty constructor
58 */
[5800]59NetworkStream::NetworkStream()
[5996]60    : DataStream()
[5647]61{
62  this->init();
[5648]63  /* initialize the references */
[9494]64  this->pInfo->nodeType = NET_UNASSIGNED;
[5647]65}
66
[6695]67
[9406]68NetworkStream::NetworkStream( int nodeType)
[5996]69{
70  this->init();
71
[9406]72  this->pInfo->nodeType = nodeType;
[5996]73
[9406]74  switch( nodeType)
75  {
76    case NET_MASTER_SERVER:
77      // init the shared network data
[9494]78      SharedNetworkData::getInstance()->setHostID(NET_ID_MASTER_SERVER);
[9656]79      this->pInfo->userId = NET_ID_MASTER_SERVER;
80      this->pInfo->nodeType = NET_MASTER_SERVER;
81
[9406]82      break;
83    case NET_PROXY_SERVER_ACTIVE:
84      // init the shared network data
[9494]85      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
[9656]86      this->pInfo->nodeType = NET_PROXY_SERVER_ACTIVE;
87
[9406]88      break;
89    case NET_PROXY_SERVER_PASSIVE:
[9494]90      // init the shared network data
91      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
[9656]92      this->pInfo->nodeType = NET_PROXY_SERVER_PASSIVE;
93
[9406]94      break;
95    case NET_CLIENT:
[9494]96      SharedNetworkData::getInstance()->setHostID(NET_ID_UNASSIGNED);
[9656]97      this->pInfo->nodeType = NET_CLIENT;
[9406]98      break;
99  }
100
101  SharedNetworkData::getInstance()->setDefaultSyncStream(this);
102
103  // get the local ip address
[9656]104  IP ip("localhost", 0);
[9406]105  this->pInfo->ip = ip;
[5649]106}
107
108
[9406]109
[9246]110/**
111 * generic init functions
112 */
[5647]113void NetworkStream::init()
114{
115  /* set the class id for the base object */
[9869]116  this->registerObject(this, NetworkStream::_objectList);
[9494]117  this->clientSocket = NULL;
[9656]118  this->clientSoftSocket = NULL;
[9494]119  this->proxySocket = NULL;
[6341]120  this->networkGameManager = NULL;
[9406]121  this->networkMonitor = NULL;
[9246]122
[9406]123  this->pInfo = new PeerInfo();
[9656]124  this->pInfo->userId = NET_UID_UNASSIGNED;
[9406]125  this->pInfo->lastAckedState = 0;
126  this->pInfo->lastRecvedState = 0;
[9656]127  this->pInfo->bLocal = true;
[9406]128
[9494]129  this->bRedirect = false;
[10114]130  this->bSoftRedirect = false;
[9406]131
132  this->currentState = 0;
[9656]133  this->redirectionUID = NET_ID_MASTER_SERVER;
[9406]134
[7954]135  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
[9246]136
[8623]137  assert( Zip::getInstance()->loadDictionary( "testdict" ) >= 0 );
138  this->dictClient = Zip::getInstance()->loadDictionary( "dict2pl_client" );
139  assert( this->dictClient >= 0 );
140  this->dictServer = Zip::getInstance()->loadDictionary( "dict2p_server" );
141  assert( this->dictServer >= 0 );
[5594]142}
143
[5647]144
[9246]145/**
146 * deconstructor
147 */
[5566]148NetworkStream::~NetworkStream()
[5598]149{
[9494]150  if ( this->clientSocket )
[6139]151  {
[9656]152    this->clientSocket->close();
153    delete this->clientSocket;
154    this->clientSocket = NULL;
[6139]155  }
[9656]156  if ( this->clientSoftSocket )
157  {
158    this->clientSoftSocket->close();
159    delete this->clientSoftSocket;
160    this->clientSoftSocket = NULL;
161  }
[9494]162  if ( this->proxySocket)
163  {
164    proxySocket->close();
165    delete proxySocket;
166    proxySocket = NULL;
167  }
[7954]168  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
[6139]169  {
[7954]170    if ( i->second.socket )
[6139]171    {
[7954]172      i->second.socket->disconnectServer();
173      delete i->second.socket;
174      i->second.socket = NULL;
[6139]175    }
[9246]176
[7954]177    if ( i->second.handshake )
[6139]178    {
[7954]179      delete i->second.handshake;
180      i->second.handshake = NULL;
[6139]181    }
[9246]182
[8623]183    if ( i->second.connectionMonitor )
184    {
185      delete i->second.connectionMonitor;
186      i->second.connectionMonitor = NULL;
187    }
[6139]188  }
[8228]189  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
190    (*it)->setNetworkStream( NULL );
[9406]191
192  if( this->pInfo)
193    delete this->pInfo;
194
195  if( this->networkMonitor)
196    delete this->networkMonitor;
[5598]197}
198
[5996]199
[9246]200/**
[9406]201 * establish a connection to a remote master server
202 * @param host: host name
203 * @param port: the port number
204 */
205void NetworkStream::connectToMasterServer(std::string host, int port)
206{
[9494]207  int node = NET_ID_MASTER_SERVER;
208  // this create the new node in the peers map
[9406]209  this->peers[node].socket = new UdpSocket( host, port );
[9494]210  this->peers[node].userId = NET_ID_MASTER_SERVER;
[9406]211
212  this->peers[node].nodeType = NET_MASTER_SERVER;
[9494]213  this->peers[node].connectionMonitor = new ConnectionMonitor( NET_ID_MASTER_SERVER );
[9406]214  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
[9656]215  this->peers[node].bLocal = true;
[9406]216}
217
218
219/**
220 * establish a connection to a remote proxy server
221 * @param host: host name
222 * @param port: the port number
223 */
[9494]224void NetworkStream::connectToProxyServer(int proxyId, std::string host, int port)
[9406]225{
[9494]226  PRINTF(0)("connect to proxy %s, this is proxyId %i\n", host.c_str(), proxyId);
[9406]227
[9494]228  // this creates the new proxyId in the peers map
229  this->peers[proxyId].socket = new UdpSocket( host, port );
230  this->peers[proxyId].userId = proxyId;
231
232  this->peers[proxyId].nodeType = NET_PROXY_SERVER_ACTIVE;
233  this->peers[proxyId].connectionMonitor = new ConnectionMonitor( proxyId );
234  this->peers[proxyId].ip = this->peers[proxyId].socket->getRemoteAddress();
[9656]235  this->peers[proxyId].bLocal = true;
[9406]236}
237
238
239/**
240 * create a server
241 * @param port: interface port for all clients
242 */
[9656]243void NetworkStream::createServer(int clientPort, int proxyPort, int clientSoftPort)
[9406]244{
[9494]245  PRINTF(0)(" Creating new Server: listening for clients on port %i and for proxies on port %i", clientPort, proxyPort);
246  this->clientSocket= new UdpServerSocket(clientPort);
[9656]247  this->clientSoftSocket= new UdpServerSocket(clientSoftPort);
[9494]248  this->proxySocket = new UdpServerSocket(proxyPort);
[9406]249}
250
251
252/**
[9246]253 * creates a new instance of the network game manager
254 */
[6695]255void NetworkStream::createNetworkGameManager()
256{
257  this->networkGameManager = NetworkGameManager::getInstance();
[9406]258
[7954]259  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
260  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
[6695]261}
262
263
[9246]264/**
265 * starts the network handshake
[9406]266 * handsakes are always initialized from the client side first. this starts the handshake and therefore is only
267 * executed as client
[9494]268 * @param userId: start handshake for this user id (optional, default == 0)
[9246]269 */
[9494]270void NetworkStream::startHandshake(int userId)
[6695]271{
[9406]272  Handshake* hs = new Handshake(this->pInfo->nodeType);
[9494]273  // fake the unique id
[9656]274  hs->setUniqueID( userId);
275  assert( this->peers[userId].handshake == NULL );
276  this->peers[userId].handshake = hs;
277  this->peers[userId].bLocal = true;
[9246]278
[9406]279  // set the preferred nick name
[9235]280  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
[9246]281
[9406]282  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getCName());
[6695]283}
284
285
[9246]286/**
287 * this functions connects a synchronizeable to the networkstream, therefore synchronizeing
288 * it all over the network and creating it on the other platforms (if and only if it is a
289 * server
[9494]290 * @param sync: the synchronizeable to add
[9246]291 */
[5996]292void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
293{
[6139]294  this->synchronizeables.push_back(&sync);
295  sync.setNetworkStream( this );
[5996]296}
297
[6695]298
[9246]299/**
300 * removes the synchronizeable from the list of synchronized entities
[9494]301 * @param sync: the syncronizeable to remove
[9246]302 */
[6139]303void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
304{
[6144]305  // removing the Synchronizeable from the List.
306  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
307  if (disconnectSynchro != this->synchronizeables.end())
308    this->synchronizeables.erase(disconnectSynchro);
[9246]309
[7954]310  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
[6139]311}
312
313
[9246]314/**
315 * this is called to process data from the network socket to the synchronizeable and vice versa
316 */
[5604]317void NetworkStream::processData()
318{
[9406]319  // create the network monitor after all the init work and before there is any connection handlings
320  if( this->networkMonitor == NULL)
[9656]321  {
[9406]322    this->networkMonitor = new NetworkMonitor(this);
[9656]323    SharedNetworkData::getInstance()->setNetworkMonitor( this->networkMonitor);
324  }
[9406]325
326
[8068]327  int tick = SDL_GetTicks();
[9246]328
[9406]329  this->currentState++;
330  // there was a wrap around
331  if( this->currentState < 0)
332  {
333    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");
334  }
[9246]335
[9494]336  if ( SharedNetworkData::getInstance()->isMasterServer())
[7954]337  {
[9406]338    // execute everytthing the master server shoudl do
[9494]339    if ( this->clientSocket )
340      this->clientSocket->update();
[9656]341    if ( this->clientSoftSocket)
342      this->clientSoftSocket->update();
[9494]343    if( this->proxySocket)
344      this->proxySocket->update();
[9246]345
[6139]346    this->updateConnectionList();
[7954]347  }
[9494]348  else if( SharedNetworkData::getInstance()->isProxyServerActive())
[9406]349  {
[9494]350    //execute everything the proxy server should do
351    if ( this->clientSocket )
352      this->clientSocket->update();
[9656]353    if ( this->clientSoftSocket)
354      this->clientSoftSocket->update();
[9494]355    if( this->proxySocket)
356      this->proxySocket->update();
[9406]357
358    this->updateConnectionList();
359  }
[9494]360
361#warning make this more modular: every proxy/master server connection should be watched for termination
362  if( !SharedNetworkData::getInstance()->isMasterServer())
[6139]363  {
[9246]364    // check if the connection is ok else terminate and remove
[9494]365    if ( !peers.empty() && peers[NET_ID_MASTER_SERVER].socket &&
366          ( !peers[NET_ID_MASTER_SERVER].socket->isOk() ||
367          peers[NET_ID_MASTER_SERVER].connectionMonitor->hasTimedOut() ) )
[6139]368    {
[9494]369      this->handleDisconnect( NET_ID_MASTER_SERVER);
[6139]370      PRINTF(1)("lost connection to server\n");
371    }
[9494]372    // check if there is a redirection command
373    if( this->bRedirect)
374    {
[9656]375      this->handleReconnect( this->redirectionUID);
[9494]376    }
[6139]377  }
378
[9494]379  this->cleanUpOldSyncList();
380  this->handleHandshakes();
[9246]381
[9406]382  // update the network monitor
383  this->networkMonitor->process();
384
[7954]385  // order of up/downstream is important!!!!
386  // don't change it
[9494]387  this->handleDownstream( tick );
388  this->handleUpstream( tick );
[9656]389
390  // process the local data of the message manager
391  MessageManager::getInstance()->processData();
392
393  if( this->bSoftRedirect)
394    this->softReconnectToServer(0, IP("localhost", 10001));
[7954]395}
396
[9246]397
398/**
[9494]399 * @brief handles incoming connections
400 *
401 * if we are a NET_MASTER_SERVER or NET_PROXY_SERVER_ACTIVE update the connection list to accept new connections (clients)
402 * start and initialize the handsake for the new clients
[9246]403 */
[7954]404void NetworkStream::updateConnectionList( )
405{
406  //check for new connections
407
[9494]408  NetworkSocket* tempNetworkSocket = NULL;
409  int userId;
[7954]410
[9494]411  if( this->clientSocket != NULL)
[6139]412  {
[9494]413    tempNetworkSocket = this->clientSocket->getNewSocket();
414
415    // we got new NET_CLIENT connecting
416    if ( tempNetworkSocket )
[6139]417    {
[9656]418      // get a userId
419//       if ( freeSocketSlots.size() > 0 )
420//       {
421//         // this should never be called
422//         userId = freeSocketSlots.back();
423//         freeSocketSlots.pop_back();
424//       }
425//       else
[9494]426      {
[9656]427        // each server (proxy and master) have an address space for new network nodes of 1000 nodes
428        // the first NET_ID_PROXY_MAX are always reserved for proxy servers
429        userId = SharedNetworkData::getInstance()->getHostID() * 1000 + NET_ID_PROXY_MAX + 1;
[9246]430
[9494]431        for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
432          if ( it->first >= userId )
433            userId = it->first + 1;
[9656]434
435        // make sure that this server only uses an address space of 1000
436        assert( userId < (SharedNetworkData::getInstance()->getHostID() + 1) * 1000);
[9494]437      }
438      // this creates a new entry in the peers list
439      peers[userId].socket = tempNetworkSocket;
440      peers[userId].nodeType = NET_CLIENT;
[9246]441
[9494]442      // handle the newly connected client
443      this->handleConnect(userId);
[9246]444
[9494]445      PRINTF(0)("New Client: %d\n", userId);
446    }
447  }
[6341]448
[9656]449  if( this->clientSoftSocket != NULL)
450  {
451    tempNetworkSocket = this->clientSoftSocket->getNewSocket();
[9406]452
[9656]453    // we got new NET_CLIENT connecting
454    if ( tempNetworkSocket )
455    {
456
457      // this creates a new entry in the peers list
458      peers[userId].socket = tempNetworkSocket;
459      peers[userId].nodeType = NET_CLIENT;
460
461      // handle the newly connected client
462      this->handleSoftConnect(userId);
463
464      PRINTF(0)("New Client softly connected: %d :D\n", userId);
465    }
466  }
467
468
[9494]469  if( this->proxySocket != NULL)
470  {
471    tempNetworkSocket = this->proxySocket->getNewSocket();
[9406]472
[9494]473    // we got new NET_PROXY_SERVER_ACTIVE connecting
474    if ( tempNetworkSocket )
[7954]475    {
[9494]476      // determine the network node id
[9656]477//       if ( freeSocketSlots.size() > 0 )
478//       {
479//         userId = freeSocketSlots.back();
480//         freeSocketSlots.pop_back();
481//       }
482//       else
[9494]483      {
484        userId = 1;
[6498]485
[9656]486        // find an empty slot within the range
487        for( int i = 0; i < NET_ID_PROXY_MAX; i++)
488        {
489          if( this->peers.find( i) == this->peers.end())
490          {
491            userId = i;
492            break;
493          }
494        }
495
496//         for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
497//           if ( it->first >= userId )
498//             userId = it->first + 1;
[9494]499      }
[9406]500
[9494]501      // this creates a new entry in the peers list
502      peers[userId].socket = tempNetworkSocket;
503      peers[userId].nodeType = NET_PROXY_SERVER_ACTIVE;
[9406]504
[9494]505      // handle the newly connected proxy server
506      this->handleConnect(userId);
[9406]507
[9494]508      PRINTF(0)("New proxy connected: %d\n", userId);
509    }
[7954]510  }
[6341]511
[9246]512
[9656]513
[7954]514  //check if connections are ok else remove them
[8228]515  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
[7954]516  {
[9246]517    if (
[7954]518          it->second.socket &&
[9246]519          (
[7954]520            !it->second.socket->isOk()  ||
521            it->second.connectionMonitor->hasTimedOut()
522          )
523       )
524    {
525      std::string reason = "disconnected";
526      if ( it->second.connectionMonitor->hasTimedOut() )
527        reason = "timeout";
528      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
529
[9656]530
[9494]531      this->handleDisconnect( it->second.userId);
[9246]532
[9656]533      if( SharedNetworkData::getInstance()->isProxyServerActive())
534        ProxyControl::getInstance()->signalLeaveClient(it->second.userId);
535
[9494]536      it++;
537      continue;
538    }
[7954]539
[9494]540    it++;
541  }
542}
[7954]543
544
[9494]545/**
546 * this handles new connections
547 * @param userId: the id of the new user node
548 */
549void NetworkStream::handleConnect( int userId)
550{
551  // create new handshake and init its variables
[9656]552  this->peers[userId].handshake = new Handshake(this->pInfo->nodeType, userId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
553  this->peers[userId].handshake->setUniqueID(userId);
[9246]554
[9656]555  this->peers[userId].connectionMonitor = new ConnectionMonitor( userId );
556  this->peers[userId].userId = userId;
557  this->peers[userId].bLocal = true;
[9246]558
[9494]559  PRINTF(0)("num sync: %d\n", synchronizeables.size());
[9246]560
[9494]561  // get the proxy server informations and write them to the handshake, if any (proxy)
562  assert( this->networkMonitor != NULL);
563  PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
564  if( pi != NULL)
565  {
[9656]566    this->peers[userId].handshake->setProxy1Address( pi->ip);
[6139]567  }
[9494]568  pi = this->networkMonitor->getSecondChoiceProxy();
569  if( pi != NULL)
[9656]570    this->peers[userId].handshake->setProxy2Address( pi->ip);
[6139]571
[9494]572  // check if the connecting client should reconnect to a proxy server
573  if( SharedNetworkData::getInstance()->isMasterServer())
[9656]574  {
575    if( this->networkMonitor->isReconnectNextClient())
576    {
577      this->peers[userId].handshake->setRedirect(true);
578      PRINTF(0)("forwarding client to proxy server because this server is saturated\n");
579    }
580  }
[6139]581
[9494]582  // the connecting node of course is a client
[9656]583  this->peers[userId].ip = this->peers[userId].socket->getRemoteAddress();
[7954]584}
[5800]585
[9246]586
[9656]587/**
588 * this handles new soft connections
589 * @param userId: the id of the new user node
590 *
591 * soft connections are connections from clients that are already in the network and don't need a new handshake etc.
592 * the state of all entitites owned by userId are not deleted and stay
593 * soft connections can not be redirected therefore they are negotiated between the to parties
594 */
595void NetworkStream::handleSoftConnect( int userId)
596{
597  // create new handshake and init its variables
598  this->peers[userId].handshake = NULL;
599  this->peers[userId].handshake->setUniqueID(userId);
[9494]600
[9656]601  this->peers[userId].connectionMonitor = new ConnectionMonitor( userId );
602  this->peers[userId].userId = userId;
603  this->peers[userId].bLocal = true;
604
605  PRINTF(0)("num sync: %d\n", synchronizeables.size());
606
607  // the connecting node of course is a client
608  this->peers[userId].ip = this->peers[userId].socket->getRemoteAddress();
609}
610
611
612
613
[9494]614/**
615 * some debug output
616 */
[7954]617void NetworkStream::debug()
618{
[9406]619  if( SharedNetworkData::getInstance()->isMasterServer()) {
620    PRINT(0)(" Host ist Master Server with ID: %i\n", this->pInfo->userId);
621  }
[9494]622  else if( SharedNetworkData::getInstance()->isProxyServerActive()) {
[9406]623    PRINT(0)(" Host ist Proxy Server with ID: %i\n", this->pInfo->userId);
624  }
625  else {
626    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
627  }
[6695]628
[9656]629  PRINT(0)(" Current number of connections is: %i\n", this->peers.size());
630  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
631  {
632    PRINT(0)("  peers[%i] with uniqueId %i and address: %s\n", it->first, it->second.userId, it->second.ip.ipString().c_str());
633  }
634  PRINT(0)("\n\n");
635
636
[7954]637  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
[6139]638  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
[5996]639  {
[7954]640    if( (*it)->beSynchronized() == true)
[9406]641      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassCName(), (*it)->getCName(),
[7954]642               (*it)->getUniqueID(), (*it)->beSynchronized());
643  }
[9406]644  PRINT(0)(" Maximal Connections: %i\n", SharedNetworkData::getInstance()->getMaxPlayer() );
[6959]645
[7954]646}
[6959]647
648
[9246]649/**
650 * @returns the number of synchronizeables registered to this stream
651 */
[7954]652int NetworkStream::getSyncCount()
653{
654  int n = 0;
655  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
656    if( (*it)->beSynchronized() == true)
657      ++n;
[5730]658
[7954]659  //return synchronizeables.size();
660  return n;
661}
[6139]662
[9246]663
[7954]664/**
[9246]665 * check if handshakes completed. if so create the network game manager else remove it again
[7954]666 */
667void NetworkStream::handleHandshakes( )
668{
669  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
670  {
671    if ( it->second.handshake )
672    {
[9406]673      // handshake finished
[7954]674      if ( it->second.handshake->completed() )
675      {
[9406]676        //handshake is correct
[7954]677        if ( it->second.handshake->ok() )
[6341]678        {
[9494]679          // write the first informations into the node so they can be read from there for case differentiation
680          it->second.nodeType = it->second.handshake->getRemoteNodeType();
681
682          // the counter part didn't mark it free for deletion yet
[7954]683          if ( !it->second.handshake->allowDel() )
[6139]684          {
[9494]685            // make sure this is a connection:
686            // - client       <==> master server
687            // - proxy server <==> master server
[9656]688            if(  SharedNetworkData::getInstance()->isClient() ||
689                 SharedNetworkData::getInstance()->isProxyServerActive() &&
690                 SharedNetworkData::getInstance()->isUserMasterServer(it->second.userId))
[9494]691            {
[9656]692              PRINTF(4)("Handshake: i am in client role\n");
[9406]693
[7954]694              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
[9406]695              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
[7954]696
[9494]697//               it->second.ip = it->second.socket->getRemoteAddress();
698
[9656]699              it->second.nodeType = it->second.handshake->getRemoteNodeType();
[9494]700              // it->second.ip = it->second.socket->getRemoteAddress();
[9406]701              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
702              this->networkMonitor->addNode(&it->second);
703              // get proxy 1 address and add it
704              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
705              // get proxy 2 address and add it
706              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
707
708              // now check if the server accepted the connection
[9494]709              if( SharedNetworkData::getInstance()->isClient() && it->second.handshake->redirect() )
710              {
711                this->bRedirect = true;
712              }
[9406]713
714              // create the new network game manager and init it
[7954]715              this->networkGameManager = NetworkGameManager::getInstance();
716              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
[9406]717              // init the new message manager
[7954]718              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
[10114]719              ObjectListBase::replaceIDMap( *(it->second.handshake->getClassIdList()) );
[6868]720            }
[7954]721
722            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
723            it->second.handshake->del();
[9494]724
[6139]725          }
726          else
727          {
[9406]728            // handshake finished registring new player
[7954]729            if ( it->second.handshake->canDel() )
[6868]730            {
[9406]731
[9494]732              if (  SharedNetworkData::getInstance()->isMasterServer() )
[7954]733              {
[9406]734                it->second.ip = it->second.socket->getRemoteAddress();
[9246]735
[9406]736                this->networkMonitor->addNode(&it->second);
737
738                this->handleNewClient( it->second.userId );
739
[9235]740                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
741                {
742                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
743                }
[7954]744              }
[9494]745              else if ( SharedNetworkData::getInstance()->isProxyServerActive() && it->second.isClient() )
[9406]746              {
[9656]747                PRINTF(4)("Handshake: Proxy in server role: connecting %i\n", it->second.userId);
[9494]748
[9406]749                it->second.ip = it->second.socket->getRemoteAddress();
[9246]750
[9406]751                this->networkMonitor->addNode(&it->second);
752
[9656]753                // work with the ProxyControl to init the new client
754                ProxyControl::getInstance()->signalNewClient( it->second.userId);
[9406]755
756                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
757                {
758                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
759                }
760              }
761
[7954]762              PRINT(0)("handshake finished delete it\n");
763              delete it->second.handshake;
764              it->second.handshake = NULL;
[6868]765            }
[6139]766          }
[7954]767
[6139]768        }
769        else
770        {
[7954]771          PRINT(1)("handshake failed!\n");
772          it->second.socket->disconnectServer();
[6139]773        }
[7954]774      }
[6139]775    }
[5996]776  }
[7954]777}
[5741]778
[9246]779
[7954]780/**
[9406]781 * this functions handles a reconnect event received from the a NET_MASTER_SERVER or NET_PROXY_SERVER
[9656]782 * @param userId
[9406]783 */
784void NetworkStream::handleReconnect(int userId)
785{
[9494]786  this->bRedirect = false;
[9656]787#warning this peer will be created if it does not yet exist: dangerous
[9494]788  PeerInfo* pInfo = &this->peers[userId];
789
[9656]790  IP proxyIP;
791  if( this->networkMonitor->isForcedReconnection())
792    proxyIP = this->networkMonitor->getForcedReconnectionIP();
793  else
794    proxyIP = pInfo->handshake->getProxy1Address();
795
[9406]796  PRINTF(0)("===============================================\n");
797  PRINTF(0)("Client is redirected to the other proxy servers\n");
[9494]798  PRINTF(0)("  user id: %i\n", userId);
[9656]799  PRINTF(0)("  connecting to: %s\n", proxyIP.ipString().c_str());
[9406]800  PRINTF(0)("===============================================\n");
801
802  // flush the old synchronization states, since the numbering could be completely different
803  pInfo->lastAckedState = 0;
804  pInfo->lastRecvedState = 0;
805
806  // disconnect from the current server and reconnect to proxy server
[9494]807  this->handleDisconnect( userId);
808  this->connectToProxyServer(NET_ID_PROXY_SERVER_01, proxyIP.ipString(), 9999);
[9656]809//   this->connectToMasterServer(proxyIP.ipString(), 9999);
[9494]810  #warning the ports are not yet integrated correctly in the ip class
[9406]811
812  // and restart the handshake
[9494]813  this->startHandshake( userId);
[9406]814}
815
816
[9656]817
[9406]818/**
[9656]819 * reconnects to another server, with full handshake
820 * @param address of the new server
821 */
822void NetworkStream::reconnectToServer(IP address)
823{
824  ///TODO make a redirection struct and push it to the network monitor
825  this->networkMonitor->setForcedReconnection(address);
826
827  // reconnect (depending on how we are connected at the moment)
828  if ( peers.find( NET_ID_MASTER_SERVER) != peers.end() )
829    this->redirectionUID = NET_ID_MASTER_SERVER;
830  else if( peers.find( NET_ID_PROXY_SERVER_01) != peers.end() )
831    this->redirectionUID = NET_ID_PROXY_SERVER_01;
832
833  this->bRedirect = true;
834}
835
836
837
838/**
839 * softly reconnecting to another server
840 * @param serverUserId the id of the client
841 * @param address  of the new server
842 */
843void NetworkStream::softReconnectToServer(int serverUserId, IP address)
844{
845//   this->networkMonitor->setForcedReconnection(address);
846//   this->handleReconnect( NET_ID_MASTER_SERVER);
847
848  // create the new udp socket and open the connection to the soft connection port
849  NetworkSocket* newSocket = new UdpSocket(address.ipString(), 10001);
850
851  // delete the synchronization state of this client for all syncs
852  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
853    (*it2)->cleanUpUser( serverUserId );
854  }
855
856  // temp save the old socket
857  NetworkSocket* oldSocket = this->peers[serverUserId].socket;
858
859  // now integrate the new socket
860  this->peers[serverUserId].socket = newSocket;
861
862  this->bSoftRedirect = false;
863  return;
864
865  // now remove the old socket
866  oldSocket->disconnectServer();
867  delete oldSocket;
868
869  // replace the old connection monitor
870  if ( this->peers[serverUserId].connectionMonitor )
871    delete this->peers[serverUserId].connectionMonitor;
872  this->peers[serverUserId].connectionMonitor = new ConnectionMonitor(serverUserId);
873
874  // remove old node from the network monitor
875  this->networkMonitor->removeNode(&this->peers[serverUserId]);
876
877}
878
879
880
881/**
882 * prepares a soft connection for a client to connect to
883 * @param userId that will connect to this server
884 */
885void NetworkStream::prepareSoftConnection(int userId)
886{
887  PRINTF(0)("prepare soft connection for userId %i\n");
888}
889
890
891
892/**
[9494]893 * handles the disconnect event
894 * @param userId id of the user to remove
895 */
896void NetworkStream::handleDisconnect( int userId )
897{
[9656]898  this->peers[userId].socket->disconnectServer();
899  delete this->peers[userId].socket;
900  this->peers[userId].socket = NULL;
[9494]901
[9656]902  if ( this->peers[userId].handshake )
903    delete this->peers[userId].handshake;
904  this->peers[userId].handshake = NULL;
[9494]905
[9656]906  if ( this->peers[userId].connectionMonitor )
907    delete this->peers[userId].connectionMonitor;
908  this->peers[userId].connectionMonitor = NULL;
[9494]909
[9656]910  // delete the synchronization state of this client for all syncs
[9494]911  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
912    (*it2)->cleanUpUser( userId );
913  }
914
915  if( SharedNetworkData::getInstance()->isMasterServer())
916    NetworkGameManager::getInstance()->signalLeftPlayer(userId);
917
918  this->freeSocketSlots.push_back( userId );
919
[9656]920  this->networkMonitor->removeNode(&this->peers[userId]);
921  this->peers.erase( userId);
[9494]922}
923
924
925/**
[7954]926 * handle upstream network traffic
[9494]927 * @param tick: seconds elapsed since last update
[7954]928 */
[8068]929void NetworkStream::handleUpstream( int tick )
[7954]930{
931  int offset;
932  int n;
[9246]933
[8068]934  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
[5802]935  {
[9246]936    offset = INTSIZE; // reserve enough space for the packet length
937
938    // continue with the next peer if this peer has no socket assigned (therefore no network)
[7954]939    if ( !peer->second.socket )
940      continue;
[9246]941
942    // header informations: current state
[7954]943    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
944    assert( n == INTSIZE );
945    offset += n;
[9246]946
947    // header informations: last acked state
[7954]948    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
949    assert( n == INTSIZE );
950    offset += n;
[9246]951
952    // header informations: last recved state
[7954]953    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
954    assert( n == INTSIZE );
955    offset += n;
[9246]956
957    // now write all synchronizeables in the packet
[7954]958    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
[5810]959    {
[9406]960
[7954]961      int oldOffset = offset;
962      Synchronizeable & sync = **it;
[9246]963
[9406]964
[9246]965      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
[9494]966      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
[7954]967        continue;
[5730]968
[9246]969      // if handshake not finished only sync handshake
[10114]970      if ( peer->second.handshake && Handshake::staticClassID() != sync.getClassID() )
[7954]971        continue;
[9246]972
[9406]973      // if we are a server (both master and proxy servers) and this is not our handshake
[9494]974      if ( ( SharedNetworkData::getInstance()->isMasterServer() ||
975             SharedNetworkData::getInstance()->isProxyServerActive() &&  peer->second.isClient())
[10114]976             && Handshake::staticClassID() == sync.getClassID() && sync.getUniqueID() != peer->second.userId )
[7954]977        continue;
[9246]978
979      /* list of synchronizeables that will never be synchronized over the network: */
980      // do not sync null parent
[10114]981      if ( NullParent::staticClassID() == sync.getClassID())
[7954]982        continue;
[6139]983
[9406]984
[10114]985      assert( sync.getClassID() != 0);
[9406]986
[7954]987      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
[9246]988
[9656]989      // server fakes uniqueid == 0 for handshake synchronizeable
[9494]990      if ( ( SharedNetworkData::getInstance()->isMasterServer() ||
991             SharedNetworkData::getInstance()->isProxyServerActive() &&  peer->second.isClient() ) &&
[9656]992             ( sync.getUniqueID() >= 1000 || sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1 + NET_ID_PROXY_MAX))
[7954]993        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
994      else
995        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
[9246]996
[9406]997
[7954]998      assert( n == INTSIZE );
999      offset += n;
[9246]1000
[9406]1001      // make space for packet size
[7954]1002      offset += INTSIZE;
[6139]1003
[7954]1004      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
1005      offset += n;
[9246]1006
[7954]1007      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
[6341]1008
[9246]1009      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
1010      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
1011      bool allZero = true;
1012      for ( int i = 0; i < n; i++ )
1013      {
1014         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
1015           allZero = false;
1016      }
1017      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
1018      // data that hast not changed
1019      if ( allZero )
1020      {
1021        offset = oldOffset;
1022      }
1023    } // all synchronizeables written
[6139]1024
[9246]1025
1026
[7954]1027    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
1028    {
1029      Synchronizeable & sync = **it;
[9246]1030
[9494]1031      // again exclude all unwanted syncs
1032      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED)
[7954]1033        continue;
[9246]1034
[7954]1035      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
1036    }
[9246]1037
1038
[7954]1039    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
[9246]1040
1041    // now compress the data with the zip library
[8623]1042    int compLength = 0;
[9494]1043    if ( SharedNetworkData::getInstance()->isMasterServer() ||
1044         SharedNetworkData::getInstance()->isProxyServerActive())
[8623]1045      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
1046    else
1047      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
[9246]1048
[8623]1049    if ( compLength <= 0 )
[7954]1050    {
1051      PRINTF(1)("compression failed!\n");
1052      continue;
1053    }
[9246]1054
[7954]1055    assert( peer->second.socket->writePacket( compBuf, compLength ) );
[9246]1056
[7954]1057    if ( this->remainingBytesToWriteToDict > 0 )
[8623]1058      writeToNewDict( buf, offset, true );
[9246]1059
[8068]1060    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
1061    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
[9246]1062
[5810]1063  }
[6139]1064}
1065
[7954]1066/**
1067 * handle downstream network traffic
1068 */
[8068]1069void NetworkStream::handleDownstream( int tick )
[6139]1070{
[7954]1071  int offset = 0;
[9246]1072
[7954]1073  int length = 0;
1074  int packetLength = 0;
1075  int compLength = 0;
1076  int uniqueId = 0;
1077  int state = 0;
1078  int ackedState = 0;
1079  int fromState = 0;
1080  int syncDataLength = 0;
[9246]1081
[7954]1082  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
[5810]1083  {
[9246]1084
[7954]1085    if ( !peer->second.socket )
1086      continue;
[5730]1087
[7954]1088    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
[6139]1089    {
[8068]1090      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
[9246]1091
[7954]1092      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
[8623]1093
[7954]1094      if ( packetLength < 4*INTSIZE )
1095      {
1096        if ( packetLength != 0 )
1097          PRINTF(1)("got too small packet: %d\n", packetLength);
1098        continue;
1099      }
[9246]1100
[7954]1101      if ( this->remainingBytesToWriteToDict > 0 )
[8623]1102        writeToNewDict( buf, packetLength, false );
[9246]1103
[7954]1104      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
1105      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
1106      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
1107      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
1108      offset = 4*INTSIZE;
[9246]1109
[8623]1110      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
[6139]1111
[9246]1112
[9406]1113      //if this is an old state drop it
[7954]1114      if ( state <= peer->second.lastRecvedState )
1115        continue;
[9246]1116
[7954]1117      if ( packetLength != length )
1118      {
1119        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
1120        peer->second.socket->disconnectServer();
1121        continue;
1122      }
[9246]1123
[9406]1124      while ( offset + 2 * INTSIZE < length )
[7954]1125      {
[9656]1126        // read the unique id of the sync
[7954]1127        assert( offset > 0 );
1128        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
1129        offset += INTSIZE;
[9246]1130
[9656]1131        // read the data length
[7954]1132        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
1133        offset += INTSIZE;
[9246]1134
[7954]1135        assert( syncDataLength > 0 );
1136        assert( syncDataLength < 10000 );
[9246]1137
[7954]1138        Synchronizeable * sync = NULL;
[9246]1139
[9406]1140        // look for the synchronizeable in question
[7954]1141        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
[9246]1142        {
[9656]1143          // client thinks his handshake has a special id: hostId * 1000 (host id of this server)
1144          if ( (*it)->getUniqueID() == uniqueId ||                                          // so this client exists already go to sync work
1145                 ( uniqueId == 0  && (*it)->getUniqueID() == peer->second.userId ) )        // so this is a Handshake!
[7954]1146          {
1147            sync = *it;
1148            break;
1149          }
1150        }
[9246]1151
[9406]1152        // this synchronizeable does not yet exist! create it
[7954]1153        if ( sync == NULL )
1154        {
1155          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
[9406]1156
1157          // if it is an old synchronizeable already removed, ignore it
[7954]1158          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
1159          {
1160            offset += syncDataLength;
1161            continue;
1162          }
[9246]1163
[9494]1164          // if the node we got this unknown sync we ignore it if:
1165          //  - the remote host is a client
1166          //  - the remote host is a proxy server and we are master server
1167          // (since it has no rights to create a new sync)
1168          if ( peers[peer->second.userId].isClient() ||
1169               (peers[peer->second.userId].isProxyServerActive() && SharedNetworkData::getInstance()->isMasterServer()))
[7954]1170          {
1171            offset += syncDataLength;
1172            continue;
1173          }
[9246]1174
[7954]1175          int leafClassId;
1176          if ( INTSIZE > length - offset )
1177          {
1178            offset += syncDataLength;
1179            continue;
1180          }
[6139]1181
[7954]1182          Converter::byteArrayToInt( buf + offset, &leafClassId );
[9246]1183
[7954]1184          assert( leafClassId != 0 );
[9246]1185
[9406]1186
[7954]1187          BaseObject * b = NULL;
1188          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
1189          /* Exception 1: NullParent */
[9869]1190          if( NullParent::staticClassID() == leafClassId || Synchronizeable::staticClassID() == leafClassId || NetworkGameManager::staticClassID() == leafClassId)
[7954]1191          {
[10114]1192            PRINTF(0)("Don't create Object with ID %d, ignored!\n", (int)leafClassId);
[7954]1193            offset += syncDataLength;
1194            continue;
1195          }
1196          else
[10114]1197                  b = Factory::fabricate( ObjectListBase::retrieveIdentity( leafClassId )  );
1198         
[7954]1199          if ( !b )
1200          {
[10114]1201            PRINTF(1)("Could not fabricate Object with classID %d\n", leafClassId);
[7954]1202            offset += syncDataLength;
1203            continue;
1204          }
[5809]1205
[9869]1206          if ( b->isA(Synchronizeable::staticClassID()) )
[7954]1207          {
1208            sync = dynamic_cast<Synchronizeable*>(b);
1209            sync->setUniqueID( uniqueId );
1210            sync->setSynchronized(true);
[9246]1211
[10114]1212            PRINTF(1)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
[7954]1213          }
1214          else
1215          {
[10114]1216            PRINTF(1)("Class with ID %d is not a synchronizeable!\n", (int)leafClassId);
[7954]1217            delete b;
1218            offset += syncDataLength;
1219            continue;
1220          }
1221        }
[6139]1222
[9246]1223
1224        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
[7954]1225        offset += n;
[6498]1226
[7954]1227      }
[9246]1228
[7954]1229      if ( offset != length )
[6139]1230      {
[7954]1231        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
1232        peer->second.socket->disconnectServer();
[6139]1233      }
[9246]1234
1235
[7954]1236      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
[6139]1237      {
[7954]1238        Synchronizeable & sync = **it;
[9246]1239
[9494]1240        if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
[7954]1241          continue;
[9246]1242
[7954]1243        sync.handleRecvState( peer->second.userId, state, fromState );
[6139]1244      }
[9246]1245
[7954]1246      assert( peer->second.lastAckedState <= ackedState );
1247      peer->second.lastAckedState = ackedState;
[9246]1248
[7954]1249      assert( peer->second.lastRecvedState < state );
1250      peer->second.lastRecvedState = state;
[8228]1251
[6139]1252    }
[9246]1253
[6139]1254  }
[9246]1255
[7954]1256}
[6139]1257
[7954]1258/**
1259 * is executed when a handshake has finished
1260 */
1261void NetworkStream::handleNewClient( int userId )
1262{
[9406]1263  // init and assign the message manager
[7954]1264  MessageManager::getInstance()->initUser( userId );
[9406]1265  // do all game relevant stuff here
[7954]1266  networkGameManager->signalNewPlayer( userId );
[5604]1267}
[6139]1268
[9406]1269
[7954]1270/**
1271 * removes old items from oldSynchronizeables
1272 */
1273void NetworkStream::cleanUpOldSyncList( )
[6139]1274{
[7954]1275  int now = SDL_GetTicks();
[9246]1276
[7954]1277  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
[6139]1278  {
[7954]1279    if ( it->second < now - 10*1000 )
1280    {
1281      std::map<int,int>::iterator delIt = it;
1282      it++;
1283      oldSynchronizeables.erase( delIt );
1284      continue;
1285    }
1286    it++;
[6139]1287  }
[7954]1288}
1289
1290/**
1291 * writes data to DATA/dicts/newdict
1292 * @param data pointer to data
1293 * @param length length
1294 */
[8623]1295void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
[7954]1296{
1297  if ( remainingBytesToWriteToDict <= 0 )
1298    return;
[9246]1299
[7954]1300  if ( length > remainingBytesToWriteToDict )
1301    length = remainingBytesToWriteToDict;
[9246]1302
[9869]1303  std::string fileName = Resources::ResourceManager::getInstance()->mainGlobalPath().name();
[7954]1304  fileName += "/dicts/newdict";
[9246]1305
[8623]1306  if ( upstream )
1307    fileName += "_upstream";
1308  else
1309    fileName += "_downstream";
[9246]1310
[7954]1311  FILE * f = fopen( fileName.c_str(), "a" );
[9246]1312
[7954]1313  if ( !f )
[6139]1314  {
[7954]1315    PRINTF(2)("could not open %s\n", fileName.c_str());
1316    remainingBytesToWriteToDict = 0;
[6139]1317    return;
1318  }
[9246]1319
[7954]1320  if ( fwrite( data, 1, length, f ) != length )
[6341]1321  {
[7954]1322    PRINTF(2)("could not write to file\n");
1323    fclose( f );
[6341]1324    return;
1325  }
[9246]1326
[7954]1327  fclose( f );
[9246]1328
1329  remainingBytesToWriteToDict -= length;
[6139]1330}
1331
1332
[6695]1333
1334
1335
1336
Note: See TracBrowser for help on using the repository browser.