Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fixed bug

File size: 16.4 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
32#include "lib/util/loading/factory.h"
33
34#include "debug.h"
35#include "class_list.h"
36#include <algorithm>
37
38/* include your own header */
39#include "network_stream.h"
40
41/* probably unnecessary */
42using namespace std;
43
44
45#define PACKAGE_SIZE  256
46
47
48NetworkStream::NetworkStream()
49    : DataStream()
50{
51  this->init();
52  /* initialize the references */
53  this->type = NET_CLIENT;
54  this->networkProtocol = new NetworkProtocol();
55  this->connectionMonitor = new ConnectionMonitor();
56}
57
58
59NetworkStream::NetworkStream( std::string host, int port )
60{
61  this->type = NET_CLIENT;
62  this->init();
63  this->peers[0].socket = new UdpSocket( host, port );
64  this->networkProtocol = new NetworkProtocol();
65  this->connectionMonitor = new ConnectionMonitor();
66  this->maxConnections = MAX_CONNECTIONS;
67}
68
69
70NetworkStream::NetworkStream( int port )
71{
72  this->type = NET_SERVER;
73  this->init();
74  this->serverSocket = new UdpServerSocket(port);
75  this->networkProtocol = new NetworkProtocol();
76  this->connectionMonitor = new ConnectionMonitor();
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  delete connectionMonitor;
124  delete networkProtocol;
125}
126
127
128void NetworkStream::createNetworkGameManager()
129{
130  this->networkGameManager = NetworkGameManager::getInstance();
131  // setUniqueID( maxCon+2 ) because we need one id for every handshake
132  // and one for handshake to reject client maxCon+1
133  this->networkGameManager->setUniqueID( this->maxConnections + 2 );
134
135}
136
137
138void NetworkStream::startHandshake()
139{
140  Handshake* hs = new Handshake(false);
141  hs->setUniqueID( 0 );
142  assert( peers[0].handshake == NULL );
143  peers[0].handshake = hs;
144  //this->connectSynchronizeable(*hs);
145  PRINTF(0)("NetworkStream: %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  this->bActive = false;
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
197
198
199  /* DOWNSTREAM */
200#if 0
201
202
203  int dataLength;
204  int reciever;
205  Header header;
206  int counter;
207
208  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
209  {
210    counter = 0;
211
212    if ( (*it)!=NULL && (*it)->beSynchronized() /*&& (*it)->getOwner() == myHostId*/ )
213    {
214      do {
215        counter++;
216
217        reciever = 0;
218#warning fix this
219dataLength = 0;
220//TODO fix
221        //dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
222
223        if ( dataLength<=0 ){
224          reciever = 0;
225          continue;
226        }
227
228        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
229
230        Header* header = (Header*)downBuffer;
231        if ( header->synchronizeableID < this->maxConnections+2 )
232        {
233          //if ( !isServer() ) PRINTF(0)("RESET UNIQUEID FROM %d TO 0 maxCon=%d\n", header->synchronizeableID, this->maxConnections);
234          header->synchronizeableID = 0;
235        }
236        else
237        {
238          //if ( !isServer() ) PRINTF(0)("UNIQUEID=%d\n", header->synchronizeableID);
239        }
240
241        if ( dataLength<=0 )
242          continue;
243
244        if ( reciever!=0 )
245        {
246          if ( reciever < 0)
247          {
248            for ( int i = 0; i<networkSockets.size(); i++)
249            {
250              if ( i!=abs(reciever) && networkSockets[i] != NULL )
251              {
252                PRINTF(0)("write %d bytes to socket %d uniqueid %d reciever %d\n", dataLength, i, (*it)->getUniqueID(), reciever);
253                networkSockets[i]->writePacket(downBuffer, dataLength);
254              }
255            }
256          }
257          else
258          {
259            if ( networkSockets[reciever] != NULL )
260            {
261              PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
262              networkSockets[reciever]->writePacket(downBuffer, dataLength);
263            }
264            else
265            {
266              PRINTF(1)("networkSockets[reciever] == NULL\n");
267            }
268          }
269        }
270        else
271        {
272          for ( int i = 0; i<networkSockets.size(); i++)
273          {
274            if ( networkSockets[i] != NULL )
275            {
276              PRINTF(5)("write %d bytes to socket %d\n", dataLength, i);
277              networkSockets[i]->writePacket(downBuffer, dataLength);
278            }
279          }
280        }
281
282      } while( reciever!=0 );
283    }
284  }
285
286  /* UPSTREAM */
287
288  for ( int i = 0; i<networkSockets.size(); i++)
289  {
290    if ( networkSockets[i] )
291    {
292      do {
293        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
294
295        if ( dataLength<=0 )
296          continue;
297
298        header = networkProtocol->extractHeader(upBuffer, dataLength);
299        dataLength -= sizeof(header);
300
301        PRINTF(5)("read %d bytes from socket uniqueID = %d\n", dataLength, header.synchronizeableID);
302
303        if ( dataLength != header.length )
304        {
305          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
306          continue;
307        }
308
309        if ( header.synchronizeableID == 0 )
310        {
311          header.synchronizeableID = i;
312        }
313
314        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
315        {
316#warning fix this
317
318          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
319          {
320            if ( (*it)->writeBytes(upBuffer+sizeof(header), dataLength, i) != header.length )
321            {
322              PRINTF(1)("%s did not read all the data id = %d!\n", (*it)->getClassName(), (*it)->getUniqueID());
323              break;
324            }
325            continue;
326          }
327
328        }
329
330      } while ( dataLength>0 );
331    }
332
333  }
334#endif
335}
336
337void NetworkStream::updateConnectionList( )
338{
339  //check for new connections
340
341  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
342
343  if ( tempNetworkSocket )
344  {
345    int clientId;
346    if ( freeSocketSlots.size() >0 )
347    {
348      clientId = freeSocketSlots.back();
349      freeSocketSlots.pop_back();
350      peers[clientId].socket = tempNetworkSocket;
351      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
352      peers[clientId].handshake->setUniqueID(clientId);
353      peers[clientId].userId = clientId;
354    } else
355    {
356      clientId = 0;
357     
358      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
359        if ( it->first >= clientId )
360          clientId = it->first + 1;
361     
362      peers[clientId].socket = tempNetworkSocket;
363      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
364      peers[clientId].handshake->setUniqueID(clientId);
365      peers[clientId].userId = clientId;
366    }
367
368    if ( clientId > this->maxConnections )
369    {
370      peers[clientId].handshake->doReject( "too many connections" );
371      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
372    }
373    else
374
375    PRINTF(0)("New Client: %d\n", clientId);
376
377    //this->connectSynchronizeable(*handshakes[clientId]);
378  }
379
380
381  //check if connections are ok else remove them
382  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
383  {
384    if ( it->second.socket && !it->second.socket->isOk() )
385    {
386      PRINTF(0)("Client is gone: %d\n", it->second.userId);
387
388      it->second.socket->disconnectServer();
389      delete it->second.socket;
390      it->second.socket = NULL;
391
392      if ( it->second.handshake )
393        delete it->second.handshake;
394      it->second.handshake = NULL;
395
396
397      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
398
399      freeSocketSlots.push_back( it->second.userId );
400
401    }
402  }
403
404
405}
406
407void NetworkStream::debug()
408{
409  if( this->isServer())
410    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
411  else
412    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
413
414  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
415  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
416  {
417    if( (*it)->beSynchronized() == true)
418      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
419               (*it)->getUniqueID(), (*it)->beSynchronized());
420  }
421  PRINT(0)(" Maximal Connections: %i\n", this->maxConnections);
422
423}
424
425
426int NetworkStream::getSyncCount()
427{
428  int n = 0;
429  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
430    if( (*it)->beSynchronized() == true)
431      ++n;
432
433  //return synchronizeables.size();
434  return n;
435}
436
437/**
438 * check if handshakes completed
439 */
440void NetworkStream::handleHandshakes( )
441{
442  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
443  {
444    if ( it->second.handshake )
445    {
446      if ( it->second.handshake->completed() )
447      {
448        if ( it->second.handshake->ok() )
449        {
450          if ( type != NET_SERVER )
451          {
452            SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
453            myHostId = SharedNetworkData::getInstance()->getHostID();
454
455            this->networkGameManager = NetworkGameManager::getInstance();
456            this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
457          }
458
459          PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
460
461
462          delete it->second.handshake;
463          it->second.handshake = NULL;
464        }
465        else
466        {
467          PRINT(1)("handshake failed!\n");
468          it->second.socket->disconnectServer();
469        }
470      }
471    }
472  }
473}
474
475/**
476 * handle upstream network traffic
477 */
478void NetworkStream::handleUpstream( )
479{
480  byte buf[UDP_PACKET_SIZE];
481  int offset;
482  int n;
483 
484  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
485  {
486    offset = INTSIZE; //make already space for length
487   
488    if ( peer->second.socket )
489      continue;
490   
491    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
492    assert( n == INTSIZE );
493    offset += n;
494   
495    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
496    assert( n == INTSIZE );
497    offset += n;
498   
499    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
500    assert( n == INTSIZE );
501    offset += n;
502   
503    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
504    {
505      Synchronizeable & sync = **it;
506     
507      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
508     
509      n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
510      assert( n == INTSIZE );
511      offset += n;
512     
513      offset += sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, 0 );
514    }
515   
516    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
517   
518    assert( peer->second.socket->writePacket( buf, offset ) );
519  }
520}
521
522/**
523 * handle downstream network traffic
524 */
525void NetworkStream::handleDownstream( )
526{
527  byte buf[UDP_PACKET_SIZE];
528  int offset = 0;
529 
530  int length = 0;
531  int packetLength = 0;
532  int uniqueId = 0;
533  int state = 0;
534  int ackedState = 0;
535  int fromState = 0;
536 
537  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
538  {
539    packetLength = peer->second.socket->readPacket( buf, UDP_PACKET_SIZE );
540   
541    assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
542    assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
543    assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
544    assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
545   
546    //if this is an old state drop it
547    if ( state <= peer->second.lastRecvedState )
548      continue;
549   
550    if ( packetLength != length )
551    {
552      PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
553      peer->second.socket->disconnectServer();
554      continue;
555    }
556   
557    offset = 4*INTSIZE;
558   
559    while ( offset < length )
560    {
561      assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
562      offset += INTSIZE;
563     
564      Synchronizeable * sync = NULL;
565     
566      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
567      {
568        if ( (*it)->getUniqueID() == uniqueId )
569        {
570          sync = *it;
571          break;
572        }
573      }
574     
575      if ( sync == NULL )
576      {
577        //TODO dont accept new object from all peers (probably only servers)
578        int leafClassId;
579        if ( INTSIZE > length - offset )
580          break;
581       
582        Converter::byteArrayToInt( buf + offset, &leafClassId );
583       
584        BaseObject * b;
585        /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
586        /* Exception 1: NullParent */
587        if( leafClassId == CL_NULL_PARENT)
588        {
589          PRINTF(1)("Can not create Class with ID %x!", (int)leafClassId);
590          break;
591        }
592        else
593          b = Factory::fabricate( (ClassID)leafClassId );
594
595        if ( !b )
596        {
597          PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
598          break;
599        }
600       
601        if ( b->isA(CL_SYNCHRONIZEABLE) )
602        {
603          sync = dynamic_cast<Synchronizeable*>(b);
604          sync->setUniqueID( uniqueId );
605          sync->setSynchronized(true);
606 
607          PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
608        }
609        else
610        {
611          PRINTF(1)("Class with ID %x is not a synchronizeable!", (int)leafClassId);
612          delete b;
613          break;
614        }
615      }
616     
617      offset += sync->setStateDiff( peer->second.userId, buf+offset, length-offset, state, fromState );
618    }
619   
620    if ( offset != length )
621    {
622      peer->second.socket->disconnectServer();
623    }
624   
625    peer->second.lastAckedState = ackedState;
626  }
627}
628
629
630
631
632
633
Note: See TracBrowser for help on using the repository browser.