Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

started implementing MessageManager

File size: 15.6 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( MAX_CONNECTIONS + 2 );
136
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  handleDownstream();
203  handleUpstream();
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());
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());
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          }
336
337          PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
338
339          delete it->second.handshake;
340          it->second.handshake = NULL;
341         
342          handleNewClient( it->second.userId );
343        }
344        else
345        {
346          PRINT(1)("handshake failed!\n");
347          it->second.socket->disconnectServer();
348        }
349      }
350    }
351  }
352}
353
354/**
355 * handle upstream network traffic
356 */
357void NetworkStream::handleUpstream( )
358{
359  byte buf[UDP_PACKET_SIZE];
360  int offset;
361  int n;
362 
363  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
364  {
365    offset = INTSIZE; //make already space for length
366   
367    if ( !peer->second.socket )
368      continue;
369   
370    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
371    assert( n == INTSIZE );
372    offset += n;
373   
374    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
375    assert( n == INTSIZE );
376    offset += n;
377   
378    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
379    assert( n == INTSIZE );
380    offset += n;
381   
382    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
383    {
384      Synchronizeable & sync = **it;
385     
386      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
387        continue;
388
389      //if handshake not finished only sync handshake
390      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
391        continue;
392     
393      if ( isServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
394        continue;
395     
396      //do not sync null parent
397      if ( sync.getLeafClassID() == CL_NULL_PARENT )
398        continue;
399
400      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
401     
402      //server fakes uniqueid=0 for handshake
403      if ( this->isServer() && sync.getUniqueID() < MAX_CONNECTIONS - 1 )
404        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
405      else
406        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
407      assert( n == INTSIZE );
408      offset += n;
409     
410      //make space for size
411      offset += INTSIZE;
412
413      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, 0 );
414      offset += n;
415     
416      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
417    }
418   
419    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
420   
421    assert( peer->second.socket->writePacket( buf, offset ) );
422    PRINTF(0)("send packet: %d userId = %d\n", offset, peer->second.userId);
423  }
424}
425
426/**
427 * handle downstream network traffic
428 */
429void NetworkStream::handleDownstream( )
430{
431  byte buf[UDP_PACKET_SIZE];
432  int offset = 0;
433 
434  int length = 0;
435  int packetLength = 0;
436  int uniqueId = 0;
437  int state = 0;
438  int ackedState = 0;
439  int fromState = 0;
440  int syncDataLength = 0;
441 
442  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
443  {
444   
445    if ( !peer->second.socket )
446      continue;
447
448    while ( packetLength = peer->second.socket->readPacket( buf, UDP_PACKET_SIZE ) > 0 )
449    {
450
451      if ( packetLength < 4*INTSIZE )
452      {
453        if ( packetLength != 0 )
454          PRINTF(1)("got too small packet: %d\n", packetLength);
455        continue;
456      }
457   
458      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
459      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
460      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
461      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
462      offset = 4*INTSIZE;
463
464      PRINTF(0)("got packet: %d, %d\n", length, packetLength);
465   
466    //if this is an old state drop it
467      if ( state <= peer->second.lastRecvedState )
468        continue;
469   
470      if ( packetLength != length )
471      {
472        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
473        peer->second.socket->disconnectServer();
474        continue;
475      }
476
477      while ( offset < length )
478      {
479        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
480        offset += INTSIZE;
481     
482        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
483        offset += INTSIZE;
484     
485        Synchronizeable * sync = NULL;
486     
487        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
488        { 
489        //                                        client thinks his handshake has id 0!!!!!
490          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
491          {
492            sync = *it;
493            break;
494          }
495        }
496     
497        if ( sync == NULL )
498        {
499          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
500          {
501            offset += syncDataLength;
502            continue;
503          }
504       
505        //TODO dont accept new object from all peers (probably only servers)
506          int leafClassId;
507          if ( INTSIZE > length - offset )
508          {
509            offset += syncDataLength;
510            continue;
511          }
512       
513          Converter::byteArrayToInt( buf + offset, &leafClassId );
514       
515          BaseObject * b;
516          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
517          /* Exception 1: NullParent */
518          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE )
519          {
520            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
521            offset += syncDataLength;
522            continue;
523          }
524          else
525            b = Factory::fabricate( (ClassID)leafClassId );
526
527          if ( !b )
528          {
529            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
530            offset += syncDataLength;
531            continue;
532          }
533       
534          if ( b->isA(CL_SYNCHRONIZEABLE) )
535          {
536            sync = dynamic_cast<Synchronizeable*>(b);
537            sync->setUniqueID( uniqueId );
538            sync->setSynchronized(true);
539 
540            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
541          }
542          else
543          {
544            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
545            delete b;
546            offset += syncDataLength;
547            continue;
548          }
549        }
550
551        offset += sync->setStateDiff( peer->second.userId, buf+offset, length-offset, state, fromState );
552      }
553   
554      if ( offset != length )
555      {
556        peer->second.socket->disconnectServer();
557      }
558   
559      peer->second.lastAckedState = ackedState;
560    }
561 
562  }
563 
564}
565
566/**
567 * is executed when a handshake has finished
568 * @todo create playable for new user
569 */
570void NetworkStream::handleNewClient( int userId )
571{
572  MessageManager::getInstance()->initUser( userId );
573}
574
575
576
577
578
579
Note: See TracBrowser for help on using the repository browser.