Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fixed bug

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