Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7767 was 7767, checked in by rennerc, 18 years ago

hover registers sync vars. started with connection monitor

File size: 16.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: claudio
13   co-programmer:
14*/
15
16
17/* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
18   For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
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 "connection_monitor.h"
28#include "synchronizeable.h"
29#include "network_game_manager.h"
30#include "shared_network_data.h"
31#include "message_manager.h"
32
33#include "network_log.h"
34
35
36#include "lib/util/loading/factory.h"
37
38#include "debug.h"
39#include "class_list.h"
40#include <algorithm>
41
42/* include your own header */
43#include "network_stream.h"
44
45/* probably unnecessary */
46using namespace std;
47
48
49#define PACKAGE_SIZE  256
50
51
52NetworkStream::NetworkStream()
53    : DataStream()
54{
55  this->init();
56  /* initialize the references */
57  this->type = NET_CLIENT;
58}
59
60
61NetworkStream::NetworkStream( std::string host, int port )
62{
63  this->type = NET_CLIENT;
64  this->init();
65  this->peers[0].socket = new UdpSocket( host, port );
66  this->peers[0].userId = 0;
67  this->peers[0].isServer = true;
68  this->peers[0].connectionMonitor = new ConnectionMonitor( 0 );
69}
70
71
72NetworkStream::NetworkStream( int port )
73{
74  this->type = NET_SERVER;
75  this->init();
76  this->serverSocket = new UdpServerSocket(port);
77  this->bActive = true;
78}
79
80
81void NetworkStream::init()
82{
83  /* set the class id for the base object */
84  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
85  this->bActive = false;
86  this->serverSocket = NULL;
87  this->networkGameManager = NULL;
88  myHostId = 0;
89  currentState = 0;
90}
91
92
93NetworkStream::~NetworkStream()
94{
95  if ( this->serverSocket )
96  {
97    serverSocket->close();
98    delete serverSocket;
99  }
100
101  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
102  {
103    if ( i->second.socket )
104    {
105      i->second.socket->disconnectServer();
106      delete i->second.socket;
107      i->second.socket = NULL;
108    }
109   
110    if ( i->second.handshake )
111    {
112      delete i->second.handshake;
113      i->second.handshake = NULL;
114    }
115  }
116 
117  if ( serverSocket )
118  {
119    delete serverSocket;
120    serverSocket = NULL;
121  }
122
123}
124
125
126void NetworkStream::createNetworkGameManager()
127{
128  this->networkGameManager = NetworkGameManager::getInstance();
129  // setUniqueID( maxCon+2 ) because we need one id for every handshake
130  // and one for handshake to reject client maxCon+1
131  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
132  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
133}
134
135
136void NetworkStream::startHandshake()
137{
138  Handshake* hs = new Handshake(false);
139  hs->setUniqueID( 0 );
140  assert( peers[0].handshake == NULL );
141  peers[0].handshake = hs;
142//   peers[0].handshake->setSynchronized( true );
143  //this->connectSynchronizeable(*hs);
144  //this->connectSynchronizeable(*hs);
145  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getName());
146}
147
148
149void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
150{
151  this->synchronizeables.push_back(&sync);
152  sync.setNetworkStream( this );
153
154  this->bActive = true;
155}
156
157
158void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
159{
160  // removing the Synchronizeable from the List.
161  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
162  if (disconnectSynchro != this->synchronizeables.end())
163    this->synchronizeables.erase(disconnectSynchro);
164 
165  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
166}
167
168
169void NetworkStream::processData()
170{
171  currentState++;
172 
173  if ( this->type == NET_SERVER )
174  {
175    if ( serverSocket )
176      serverSocket->update();
177   
178    this->updateConnectionList();
179  }
180  else
181  {
182    if ( peers[0].socket && !peers[0].socket->isOk() )
183    {
184      PRINTF(1)("lost connection to server\n");
185
186      peers[0].socket->disconnectServer();
187      delete peers[0].socket;
188      peers[0].socket = NULL;
189
190      if ( peers[0].handshake )
191        delete peers[0].handshake;
192      peers[0].handshake = NULL;
193    }
194  }
195
196  cleanUpOldSyncList();
197  handleHandshakes();
198  handleUpstream();
199  handleDownstream();
200
201}
202
203void NetworkStream::updateConnectionList( )
204{
205  //check for new connections
206
207  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
208
209  if ( tempNetworkSocket )
210  {
211    int clientId;
212    if ( freeSocketSlots.size() >0 )
213    {
214      clientId = freeSocketSlots.back();
215      freeSocketSlots.pop_back();
216      peers[clientId].socket = tempNetworkSocket;
217      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID() );
218      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
219      peers[clientId].handshake->setUniqueID(clientId);
220      peers[clientId].userId = clientId;
221      peers[clientId].isServer = false;
222    } else
223    {
224      clientId = 1;
225     
226      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
227        if ( it->first >= clientId )
228          clientId = it->first + 1;
229     
230      peers[clientId].socket = tempNetworkSocket;
231      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
232      peers[clientId].handshake->setUniqueID(clientId);
233      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
234      peers[clientId].userId = clientId;
235      peers[clientId].isServer = false;
236     
237      PRINTF(0)("num sync: %d\n", synchronizeables.size());
238    }
239
240    if ( clientId > MAX_CONNECTIONS )
241    {
242      peers[clientId].handshake->doReject( "too many connections" );
243      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
244    }
245    else
246
247    PRINTF(0)("New Client: %d\n", clientId);
248
249    //this->connectSynchronizeable(*handshakes[clientId]);
250  }
251
252
253  //check if connections are ok else remove them
254  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
255  {
256    //TODO check for timeout
257    if ( 
258          (it->second.socket && !it->second.socket->isOk() ) ||
259          it->second.connectionMonitor->hasTimedOut()
260       )
261    {
262      PRINTF(0)("Client is gone: %d\n", it->second.userId);
263
264      it->second.socket->disconnectServer();
265      delete it->second.socket;
266      it->second.socket = NULL;
267
268      if ( it->second.handshake )
269        delete it->second.handshake;
270      it->second.handshake = NULL;
271     
272      for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )
273      {
274        (*it2)->cleanUpUser( it->second.userId );
275      }
276
277      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
278
279      freeSocketSlots.push_back( it->second.userId );
280
281    }
282  }
283
284
285}
286
287void NetworkStream::debug()
288{
289  if( this->isServer())
290    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
291  else
292    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
293
294  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
295  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
296  {
297    if( (*it)->beSynchronized() == true)
298      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
299               (*it)->getUniqueID(), (*it)->beSynchronized());
300  }
301  PRINT(0)(" Maximal Connections: %i\n", MAX_CONNECTIONS );
302
303}
304
305
306int NetworkStream::getSyncCount()
307{
308  int n = 0;
309  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
310    if( (*it)->beSynchronized() == true)
311      ++n;
312
313  //return synchronizeables.size();
314  return n;
315}
316
317/**
318 * check if handshakes completed
319 */
320void NetworkStream::handleHandshakes( )
321{
322  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
323  {
324    if ( it->second.handshake )
325    {
326      if ( it->second.handshake->completed() )
327      {
328        if ( it->second.handshake->ok() )
329        {
330          if ( type != NET_SERVER )
331          {
332            SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
333            myHostId = SharedNetworkData::getInstance()->getHostID();
334
335            this->networkGameManager = NetworkGameManager::getInstance();
336            this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
337            MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
338          }
339
340          PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
341
342          delete it->second.handshake;
343          it->second.handshake = NULL;
344         
345          handleNewClient( it->second.userId );
346        }
347        else
348        {
349          PRINT(1)("handshake failed!\n");
350          it->second.socket->disconnectServer();
351        }
352      }
353    }
354  }
355}
356
357/**
358 * handle upstream network traffic
359 */
360void NetworkStream::handleUpstream( )
361{
362  byte buf[UDP_PACKET_SIZE];
363  int offset;
364  int n;
365 
366  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
367  {
368    offset = INTSIZE; //make already space for length
369   
370    if ( !peer->second.socket )
371      continue;
372   
373    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
374    assert( n == INTSIZE );
375    offset += n;
376   
377    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
378    assert( n == INTSIZE );
379    offset += n;
380   
381    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
382    assert( n == INTSIZE );
383    offset += n;
384   
385    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
386    {
387      Synchronizeable & sync = **it;
388     
389      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
390        continue;
391
392      //if handshake not finished only sync handshake
393      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
394        continue;
395     
396      if ( isServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
397        continue;
398     
399      //do not sync null parent
400      if ( sync.getLeafClassID() == CL_NULL_PARENT )
401        continue;
402
403      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
404     
405      //server fakes uniqueid=0 for handshake
406      if ( this->isServer() && sync.getUniqueID() < MAX_CONNECTIONS - 1 )
407        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
408      else
409        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
410      assert( n == INTSIZE );
411      offset += n;
412     
413      //make space for size
414      offset += INTSIZE;
415
416      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
417      offset += n;
418     
419      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
420    }
421   
422    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
423   
424    assert( peer->second.socket->writePacket( buf, offset ) );
425   
426    peer->second.connectionMonitor->processUnzippedOutgoingPacket( buf, offset, currentState );
427   
428    NETPRINTF(n)("send packet: %d userId = %d\n", offset, peer->second.userId);
429  }
430}
431
432/**
433 * handle downstream network traffic
434 */
435void NetworkStream::handleDownstream( )
436{
437  byte buf[UDP_PACKET_SIZE];
438  int offset = 0;
439 
440  int length = 0;
441  int packetLength = 0;
442  int uniqueId = 0;
443  int state = 0;
444  int ackedState = 0;
445  int fromState = 0;
446  int syncDataLength = 0;
447 
448  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
449  {
450   
451    if ( !peer->second.socket )
452      continue;
453
454    while ( 0 < (packetLength = peer->second.socket->readPacket( buf, UDP_PACKET_SIZE )) )
455    {
456
457      if ( packetLength < 4*INTSIZE )
458      {
459        if ( packetLength != 0 )
460          PRINTF(1)("got too small packet: %d\n", packetLength);
461        continue;
462      }
463   
464      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
465      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
466      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
467      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
468      NETPRINTF(n)("ackedstate: %d\n", ackedState);
469      offset = 4*INTSIZE;
470
471      NETPRINTF(n)("got packet: %d, %d\n", length, packetLength);
472   
473    //if this is an old state drop it
474      if ( state <= peer->second.lastRecvedState )
475        continue;
476   
477      if ( packetLength != length )
478      {
479        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
480        peer->second.socket->disconnectServer();
481        continue;
482      }
483     
484      while ( offset < length )
485      {
486        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
487        offset += INTSIZE;
488     
489        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
490        offset += INTSIZE;
491     
492        Synchronizeable * sync = NULL;
493       
494        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
495        { 
496        //                                        client thinks his handshake has id 0!!!!!
497          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
498          {
499            sync = *it;
500            break;
501          }
502        }
503       
504        if ( sync == NULL )
505        {
506          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
507          {
508            offset += syncDataLength;
509            continue;
510          }
511
512          if ( !peers[peer->second.userId].isServer )
513          {
514            offset += syncDataLength;
515            continue;
516          }
517         
518          int leafClassId;
519          if ( INTSIZE > length - offset )
520          {
521            offset += syncDataLength;
522            continue;
523          }
524
525          Converter::byteArrayToInt( buf + offset, &leafClassId );
526       
527          BaseObject * b;
528          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
529          /* Exception 1: NullParent */
530          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE )
531          {
532            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
533            offset += syncDataLength;
534            continue;
535          }
536          else
537            b = Factory::fabricate( (ClassID)leafClassId );
538
539          if ( !b )
540          {
541            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
542            offset += syncDataLength;
543            continue;
544          }
545
546          if ( b->isA(CL_SYNCHRONIZEABLE) )
547          {
548            sync = dynamic_cast<Synchronizeable*>(b);
549            sync->setUniqueID( uniqueId );
550            sync->setSynchronized(true);
551 
552            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
553          }
554          else
555          {
556            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
557            delete b;
558            offset += syncDataLength;
559            continue;
560          }
561        }
562
563        offset += sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState ); 
564      }
565     
566      if ( offset != length )
567      {
568        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
569        peer->second.socket->disconnectServer();
570      }
571     
572      peer->second.connectionMonitor->processUnzippedIncomingPacket( buf, offset, currentState, ackedState );
573   
574      peer->second.lastAckedState = ackedState;
575      peer->second.lastRecvedState = state;
576     
577    }
578 
579  }
580 
581}
582
583/**
584 * is executed when a handshake has finished
585 * @todo create playable for new user
586 */
587void NetworkStream::handleNewClient( int userId )
588{
589  MessageManager::getInstance()->initUser( userId );
590 
591  networkGameManager->signalNewPlayer( userId );
592}
593
594/**
595 * removes old items from oldSynchronizeables
596 */
597void NetworkStream::cleanUpOldSyncList( )
598{
599  int now = SDL_GetTicks();
600 
601  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
602  {
603    if ( it->second < now - 10*1000 )
604    {
605      std::map<int,int>::iterator delIt = it;
606      it++;
607      oldSynchronizeables.erase( delIt );
608      continue;
609    }
610    it++;
611  }
612}
613
614
615
616
617
618
Note: See TracBrowser for help on using the repository browser.