Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

working on the client number < 3 bug

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