Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6660 was 6660, checked in by patrick, 18 years ago

network: some more nodes connected to the NetworkStream no sync yet

File size: 11.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 "network_socket.h"
26#include "connection_monitor.h"
27#include "synchronizeable.h"
28#include "network_manager.h"
29#include "network_game_manager.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            NetworkManager::getInstance()->setHostID( handshakes[i]->getHostId() );
197            myHostId = NetworkManager::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  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
234  {
235    if ( (*it)!=NULL && (*it)->beSynchronized() /*&& (*it)->getOwner() == myHostId*/ )
236    {
237      do {
238        reciever = 0;
239        dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
240
241
242        if ( dataLength<=0 ){
243          reciever = 0;
244          continue;
245        }
246
247        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
248
249        Header* header = (Header*)downBuffer;
250        if ( header->synchronizeableID < this->maxConnections+2 )
251        {
252          //if ( !isServer() ) PRINTF(0)("RESET UNIQUEID FROM %d TO 0 maxCon=%d\n", header->synchronizeableID, this->maxConnections);
253          header->synchronizeableID = 0;
254        }
255        else
256        {
257          //if ( !isServer() ) PRINTF(0)("UNIQUEID=%d\n", header->synchronizeableID);
258        }
259
260        if ( dataLength<=0 )
261          continue;
262
263        if ( reciever!=0 )
264        {
265          if ( networkSockets[reciever] != NULL )
266          {
267            PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
268            networkSockets[reciever]->writePacket(downBuffer, dataLength);
269          }
270          else
271          {
272            PRINTF(1)("networkSockets[reciever] == NULL\n");
273          }
274        }
275        else
276        {
277          for ( int i = 0; i<networkSockets.size(); i++)
278          {
279            if ( networkSockets[i] != NULL )
280            {
281              PRINTF(5)("write %d bytes to socket %d\n", dataLength, i);
282              networkSockets[i]->writePacket(downBuffer, dataLength);
283            }
284          }
285        }
286
287      } while( reciever!=0 );
288    }
289  }
290
291  /* UPSTREAM */
292
293  for ( int i = 0; i<networkSockets.size(); i++)
294  {
295    if ( networkSockets[i] )
296    {
297      do {
298        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
299
300        if ( dataLength<=0 )
301          continue;
302
303        header = networkProtocol->extractHeader(upBuffer, dataLength);
304        dataLength -= sizeof(header);
305
306        PRINTF(5)("read %d bytes from socket uniqueID = %d\n", dataLength, header.synchronizeableID);
307
308        if ( dataLength != header.length )
309        {
310          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
311          continue;
312        }
313
314        if ( header.synchronizeableID == 0 )
315        {
316          header.synchronizeableID = i;
317        }
318
319        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
320        {
321          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
322          {
323            if ( (*it)->writeBytes(upBuffer+sizeof(header), dataLength, i) != header.length )
324            {
325              PRINTF(1)("%s did not read all the data id = %d!\n", (*it)->getClassName(), (*it)->getUniqueID());
326              break;
327            }
328            continue;
329          }
330        }
331
332      } while ( dataLength>0 );
333    }
334  }
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      networkSockets[clientId] = tempNetworkSocket;
351      handshakes[clientId] = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
352      handshakes[clientId]->setUniqueID(clientId);
353    } else
354    {
355      clientId = networkSockets.size();
356      networkSockets.push_back(tempNetworkSocket);
357      Handshake* tHs = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
358      tHs->setUniqueID(clientId);
359      handshakes.push_back(tHs);
360    }
361
362    if ( clientId > this->maxConnections )
363    {
364      handshakes[clientId]->doReject();
365      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
366    }
367    else
368
369    PRINTF(0)("New Client: %d\n", clientId);
370
371    this->connectSynchronizeable(*handshakes[clientId]);
372  }
373
374
375  //check if connections are ok else remove them
376  for ( int i = 1; i<networkSockets.size(); i++)
377  {
378    if ( networkSockets[i] && !networkSockets[i]->isOk() )
379    {
380      //TODO: tell EntityManager that this player left the game
381      PRINTF(0)("Client is gone: %d\n", i);
382
383      //delete networkSockets[i];
384      networkSockets[i]->disconnectServer();
385      networkSockets[i]->destroy();
386      networkSockets[i] = NULL;
387
388      if ( handshakes[i] )
389        delete handshakes[i];
390      handshakes[i] = NULL;
391
392      if ( i == networkSockets.size()-1 )
393      {
394        networkSockets.pop_back();
395        handshakes.pop_back();
396      }
397      else
398      {
399        freeSocketSlots.push_back(i);
400      }
401    }
402  }
403
404
405}
406
407void NetworkStream::setMaxConnections( int n )
408{
409  if ( !this->isServer() )
410  {
411    PRINTF(1)("Cannot set maxConnections because I am no server.\n");
412  }
413  if ( this->networkSockets.size() > 1 )
414  {
415    PRINTF(1)("Cannot set maxConnections because there are already %d connections.\n", this->networkSockets.size());
416    return;
417  }
418
419  if ( n > MAX_CONNECTIONS )
420  {
421    PRINTF(1)("Cannot set maxConnectiosn to %d because of hardcoded limit %d\n", n, MAX_CONNECTIONS);
422    return;
423  }
424
425  this->maxConnections = n;
426  this->networkGameManager->setUniqueID( n+2 );
427}
428
429
430
431void NetworkStream::debug()
432{
433  if( this->isServer())
434    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
435  else
436    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
437
438  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
439  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
440  {
441    if( (*it)->beSynchronized() == true)
442      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
443               (*it)->getUniqueID(), (*it)->beSynchronized());
444  }
445  PRINT(0)(" Maximal Connections: %i\n", this->maxConnections);
446
447}
448
449
450
451
452
453
454
455
456
457
458
459
460
461
Note: See TracBrowser for help on using the repository browser.