Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fix for bether performance

File size: 16.0 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, 0 );
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    PRINTF(0)("send packet: %d userId = %d\n", offset, peer->second.userId);
424  }
425}
426
427/**
428 * handle downstream network traffic
429 */
430void NetworkStream::handleDownstream( )
431{
432  byte buf[UDP_PACKET_SIZE];
433  int offset = 0;
434 
435  int length = 0;
436  int packetLength = 0;
437  int uniqueId = 0;
438  int state = 0;
439  int ackedState = 0;
440  int fromState = 0;
441  int syncDataLength = 0;
442 
443  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
444  {
445   
446    if ( !peer->second.socket )
447      continue;
448
449    while ( 0 < (packetLength = peer->second.socket->readPacket( buf, UDP_PACKET_SIZE )) )
450    {
451
452      if ( packetLength < 4*INTSIZE )
453      {
454        if ( packetLength != 0 )
455          PRINTF(1)("got too small packet: %d\n", packetLength);
456        continue;
457      }
458   
459      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
460      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
461      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
462      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
463      offset = 4*INTSIZE;
464
465      PRINTF(0)("got packet: %d, %d\n", length, packetLength);
466   
467    //if this is an old state drop it
468      if ( state <= peer->second.lastRecvedState )
469        continue;
470   
471      if ( packetLength != length )
472      {
473        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
474        peer->second.socket->disconnectServer();
475        continue;
476      }
477
478      while ( offset < length )
479      {
480        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
481        offset += INTSIZE;
482     
483        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
484        offset += INTSIZE;
485     
486        Synchronizeable * sync = NULL;
487     
488        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
489        { 
490        //                                        client thinks his handshake has id 0!!!!!
491          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
492          {
493            sync = *it;
494            break;
495          }
496        }
497     
498        if ( sync == NULL )
499        {
500          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
501          {
502            offset += syncDataLength;
503            continue;
504          }
505       
506        //TODO dont accept new object from all peers (probably only servers)
507          int leafClassId;
508          if ( INTSIZE > length - offset )
509          {
510            offset += syncDataLength;
511            continue;
512          }
513       
514          Converter::byteArrayToInt( buf + offset, &leafClassId );
515       
516          BaseObject * b;
517          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
518          /* Exception 1: NullParent */
519          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE )
520          {
521            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
522            offset += syncDataLength;
523            continue;
524          }
525          else
526            b = Factory::fabricate( (ClassID)leafClassId );
527
528          if ( !b )
529          {
530            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
531            offset += syncDataLength;
532            continue;
533          }
534       
535          if ( b->isA(CL_SYNCHRONIZEABLE) )
536          {
537            sync = dynamic_cast<Synchronizeable*>(b);
538            sync->setUniqueID( uniqueId );
539            sync->setSynchronized(true);
540 
541            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
542          }
543          else
544          {
545            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
546            delete b;
547            offset += syncDataLength;
548            continue;
549          }
550        }
551
552        offset += sync->setStateDiff( peer->second.userId, buf+offset, length-offset, state, fromState );
553      }
554   
555      if ( offset != length )
556      {
557        peer->second.socket->disconnectServer();
558      }
559   
560      peer->second.lastAckedState = ackedState;
561    }
562 
563  }
564 
565}
566
567/**
568 * is executed when a handshake has finished
569 * @todo create playable for new user
570 */
571#include "world_entities/space_ships/space_ship.h"
572void NetworkStream::handleNewClient( int userId )
573{
574  MessageManager::getInstance()->initUser( userId );
575 
576  networkGameManager->signalNewPlayer( userId );
577}
578
579
580
581
582
583
Note: See TracBrowser for help on using the repository browser.