Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/network_stream.cc @ 7440

Last change on this file since 7440 was 6959, checked in by patrick, 19 years ago

trunk: merged network branche into trunk

File size: 12.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 "network_socket.h"
26#include "connection_monitor.h"
27#include "synchronizeable.h"
28#include "network_game_manager.h"
29#include "shared_network_data.h"
30
31#include "debug.h"
32#include "class_list.h"
33#include <algorithm>
34
35/* include your own header */
36#include "network_stream.h"
37
38/* probably unnecessary */
39using namespace std;
40
41
42#define PACKAGE_SIZE  256
43
44
45NetworkStream::NetworkStream()
46    : DataStream()
47{
48  this->init();
49  /* initialize the references */
50  this->type = NET_CLIENT;
51  this->networkProtocol = new NetworkProtocol();
52  this->connectionMonitor = new ConnectionMonitor();
53}
54
55
56NetworkStream::NetworkStream(IPaddress& address)
57{
58  this->type = NET_CLIENT;
59  this->init();
60  this->networkSockets.push_back(new NetworkSocket(address));
61  this->networkProtocol = new NetworkProtocol();
62  this->connectionMonitor = new ConnectionMonitor();
63  this->maxConnections = 1;
64}
65
66
67NetworkStream::NetworkStream(unsigned int port)
68{
69  this->type = NET_SERVER;
70  this->init();
71  this->serverSocket = new ServerSocket(port);
72  this->networkProtocol = new NetworkProtocol();
73  this->connectionMonitor = new ConnectionMonitor();
74  this->networkSockets.push_back( NULL );
75  this->networkSockets[0] = NULL; //TODO: remove this
76  this->handshakes.push_back( NULL );
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}
90
91
92NetworkStream::~NetworkStream()
93{
94  if ( this->serverSocket )
95  {
96    serverSocket->close();
97    delete serverSocket;
98  }
99
100  for (NetworkSocketVector::iterator i = networkSockets.begin(); i!=networkSockets.end(); i++)
101  {
102    if ( *i )
103    {
104      (*i)->disconnectServer();
105      (*i)->destroy();
106    }
107  }
108
109  for (HandshakeVector::iterator i = handshakes.begin(); i!=handshakes.end(); i++)
110  {
111    if ( *i )
112    {
113      delete (*i);
114    }
115  }
116
117  delete connectionMonitor;
118  delete networkProtocol;
119}
120
121
122void NetworkStream::createNetworkGameManager()
123{
124  this->networkGameManager = NetworkGameManager::getInstance();
125  // setUniqueID( maxCon+2 ) because we need one id for every handshake
126  // and one for handshake to reject client maxCon+1
127  this->networkGameManager->setUniqueID( this->maxConnections + 2 );
128  //this->connectSynchronizeable( *(this->networkGameManager) );
129  this->setMaxConnections( 10 );
130}
131
132
133void NetworkStream::startHandshake()
134{
135  Handshake* hs = new Handshake(false);
136  hs->setUniqueID( 0 );
137  this->handshakes.push_back(hs);
138  //this->connectSynchronizeable(*hs);
139  PRINTF(0)("NetworkStream: %s\n", hs->getName());
140}
141
142
143void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
144{
145  this->synchronizeables.push_back(&sync);
146  sync.setNetworkStream( this );
147
148  if( this->networkSockets.size()>0 )
149    this->bActive = true;
150}
151
152
153void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
154{
155  // removing the Synchronizeable from the List.
156  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
157  if (disconnectSynchro != this->synchronizeables.end())
158    this->synchronizeables.erase(disconnectSynchro);
159
160  if( this->networkSockets.size()<=0 )
161    this->bActive = false;
162}
163
164
165void NetworkStream::processData()
166{
167  if ( this->type == NET_SERVER )
168    this->updateConnectionList();
169  else
170  {
171    if ( networkSockets[0] && !networkSockets[0]->isOk() )
172    {
173      PRINTF(1)("lost connection to server\n");
174
175      //delete networkSockets[i];
176      networkSockets[0]->disconnectServer();
177      networkSockets[0]->destroy();
178      networkSockets[0] = NULL;
179
180      if ( handshakes[0] )
181        delete handshakes[0];
182      handshakes[0] = NULL;
183    }
184  }
185
186  for (int i = 0; i<handshakes.size(); i++)
187  {
188    if ( handshakes[i] )
189    {
190      if ( handshakes[i]->completed() )
191      {
192        if ( handshakes[i]->ok() )
193        {
194          if ( type != NET_SERVER )
195          {
196            SharedNetworkData::getInstance()->setHostID( handshakes[i]->getHostId() );
197            myHostId = SharedNetworkData::getInstance()->getHostID();
198
199            this->networkGameManager = NetworkGameManager::getInstance();
200            this->networkGameManager->setUniqueID( handshakes[i]->getNetworkGameManagerId() );
201            //this->connectSynchronizeable( *(this->networkGameManager) );
202          }
203          else
204          {
205
206          }
207          PRINT(0)("handshake finished id=%d\n", handshakes[i]->getNetworkGameManagerId());
208
209
210          delete handshakes[i];
211          handshakes[i] = NULL;
212        }
213        else
214        {
215          PRINT(1)("handshake failed!\n");
216          networkSockets[i]->disconnectServer();
217          delete handshakes[i];
218          handshakes[i] = NULL;
219          //TODO: handle error
220        }
221      }
222    }
223  }
224
225
226  /* DOWNSTREAM */
227
228
229
230  int dataLength;
231  int reciever;
232  Header header;
233  int counter;
234
235  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
236  {
237    counter = 0;
238
239    if ( (*it)!=NULL && (*it)->beSynchronized() /*&& (*it)->getOwner() == myHostId*/ )
240    {
241      do {
242        counter++;
243
244        //check for endless loop
245        if ( counter > 50 )
246        {
247          PRINTF(1)("there seems to be an error in readBytes of %s\n", (*it)->getClassName());
248          assert(false);
249        }
250
251        reciever = 0;
252        dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
253
254        if ( dataLength<=0 ){
255          reciever = 0;
256          continue;
257        }
258
259        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
260
261        Header* header = (Header*)downBuffer;
262        if ( header->synchronizeableID < this->maxConnections+2 )
263        {
264          //if ( !isServer() ) PRINTF(0)("RESET UNIQUEID FROM %d TO 0 maxCon=%d\n", header->synchronizeableID, this->maxConnections);
265          header->synchronizeableID = 0;
266        }
267        else
268        {
269          //if ( !isServer() ) PRINTF(0)("UNIQUEID=%d\n", header->synchronizeableID);
270        }
271
272        if ( dataLength<=0 )
273          continue;
274
275        if ( reciever!=0 )
276        {
277          if ( reciever < 0)
278          {
279            for ( int i = 0; i<networkSockets.size(); i++)
280            {
281              if ( i!=abs(reciever) && networkSockets[i] != NULL )
282              {
283                PRINTF(0)("write %d bytes to socket %d uniqueid %d reciever %d\n", dataLength, i, (*it)->getUniqueID(), reciever);
284                networkSockets[i]->writePacket(downBuffer, dataLength);
285              }
286            }
287          }
288          else
289          {
290            if ( networkSockets[reciever] != NULL )
291            {
292              PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
293              networkSockets[reciever]->writePacket(downBuffer, dataLength);
294            }
295            else
296            {
297              PRINTF(1)("networkSockets[reciever] == NULL\n");
298            }
299          }
300        }
301        else
302        {
303          for ( int i = 0; i<networkSockets.size(); i++)
304          {
305            if ( networkSockets[i] != NULL )
306            {
307              PRINTF(5)("write %d bytes to socket %d\n", dataLength, i);
308              networkSockets[i]->writePacket(downBuffer, dataLength);
309            }
310          }
311        }
312
313      } while( reciever!=0 );
314    }
315  }
316
317  /* UPSTREAM */
318
319  for ( int i = 0; i<networkSockets.size(); i++)
320  {
321    if ( networkSockets[i] )
322    {
323      do {
324        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
325
326        if ( dataLength<=0 )
327          continue;
328
329        header = networkProtocol->extractHeader(upBuffer, dataLength);
330        dataLength -= sizeof(header);
331
332        PRINTF(5)("read %d bytes from socket uniqueID = %d\n", dataLength, header.synchronizeableID);
333
334        if ( dataLength != header.length )
335        {
336          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
337          continue;
338        }
339
340        if ( header.synchronizeableID == 0 )
341        {
342          header.synchronizeableID = i;
343        }
344
345        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
346        {
347          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
348          {
349            if ( (*it)->writeBytes(upBuffer+sizeof(header), dataLength, i) != header.length )
350            {
351              PRINTF(1)("%s did not read all the data id = %d!\n", (*it)->getClassName(), (*it)->getUniqueID());
352              break;
353            }
354            continue;
355          }
356        }
357
358      } while ( dataLength>0 );
359    }
360  }
361}
362
363void NetworkStream::updateConnectionList( )
364{
365  //check for new connections
366
367  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
368
369  if ( tempNetworkSocket )
370  {
371    int clientId;
372    if ( freeSocketSlots.size() >0 )
373    {
374      clientId = freeSocketSlots.back();
375      freeSocketSlots.pop_back();
376      networkSockets[clientId] = tempNetworkSocket;
377      handshakes[clientId] = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
378      handshakes[clientId]->setUniqueID(clientId);
379    } else
380    {
381      clientId = networkSockets.size();
382      networkSockets.push_back(tempNetworkSocket);
383      Handshake* tHs = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
384      tHs->setUniqueID(clientId);
385      handshakes.push_back(tHs);
386    }
387
388    if ( clientId > this->maxConnections )
389    {
390      handshakes[clientId]->doReject();
391      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
392    }
393    else
394
395    PRINTF(0)("New Client: %d\n", clientId);
396
397    //this->connectSynchronizeable(*handshakes[clientId]);
398  }
399
400
401  //check if connections are ok else remove them
402  for ( int i = 1; i<networkSockets.size(); i++)
403  {
404    if ( networkSockets[i] && !networkSockets[i]->isOk() )
405    {
406      //TODO: tell EntityManager that this player left the game
407      PRINTF(0)("Client is gone: %d\n", i);
408
409      //delete networkSockets[i];
410      networkSockets[i]->disconnectServer();
411      networkSockets[i]->destroy();
412      networkSockets[i] = NULL;
413
414      if ( handshakes[i] )
415        delete handshakes[i];
416      handshakes[i] = NULL;
417
418
419      NetworkGameManager::getInstance()->signalLeftPlayer(i);
420
421      if ( i == networkSockets.size()-1 )
422      {
423        networkSockets.pop_back();
424        handshakes.pop_back();
425      }
426      else
427      {
428        freeSocketSlots.push_back(i);
429      }
430    }
431  }
432
433
434}
435
436void NetworkStream::setMaxConnections( int n )
437{
438  if ( !this->isServer() )
439  {
440    PRINTF(1)("Cannot set maxConnections because I am no server.\n");
441  }
442  if ( this->networkSockets.size() > 1 )
443  {
444    PRINTF(1)("Cannot set maxConnections because there are already %d connections.\n", this->networkSockets.size());
445    return;
446  }
447
448  if ( n > MAX_CONNECTIONS )
449  {
450    PRINTF(1)("Cannot set maxConnectiosn to %d because of hardcoded limit %d\n", n, MAX_CONNECTIONS);
451    return;
452  }
453
454  this->maxConnections = n;
455  this->networkGameManager->setUniqueID( n+2 );
456}
457
458
459
460void NetworkStream::debug()
461{
462  if( this->isServer())
463    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
464  else
465    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
466
467  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
468  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
469  {
470    if( (*it)->beSynchronized() == true)
471      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
472               (*it)->getUniqueID(), (*it)->beSynchronized());
473  }
474  PRINT(0)(" Maximal Connections: %i\n", this->maxConnections);
475
476}
477
478
479int NetworkStream::getSyncCount()
480{
481  int n = 0;
482  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
483    if( (*it)->beSynchronized() == true)
484      ++n;
485
486  //return synchronizeables.size();
487  return n;
488}
489
490
491
492
493
494
Note: See TracBrowser for help on using the repository browser.