Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fixed some bugs

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