Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

new approach: the reconnection is handled from a different point in the network process

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