Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

network: debug function for NetworkStream and connection

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