Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6868 was 6868, checked in by bensch, 18 years ago

orxonox/trunk: merged the Network back to the trunk.
merged with command
svn merge https://svn.orxonox.net/orxonox/branches/network . -r6817:HEAD
no conflicts

File size: 12.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
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 = 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 ( reciever < 0)
266          {
267            for ( int i = 0; i<networkSockets.size(); i++)
268            {
269              if ( i!=-reciever && networkSockets[i] != NULL )
270              {
271                PRINTF(5)("write %d bytes to socket %d\n", dataLength, i);
272                networkSockets[i]->writePacket(downBuffer, dataLength);
273              }
274            }
275          }
276          else
277          {
278            if ( networkSockets[reciever] != NULL )
279            {
280              PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
281              networkSockets[reciever]->writePacket(downBuffer, dataLength);
282            }
283            else
284            {
285              PRINTF(1)("networkSockets[reciever] == NULL\n");
286            }
287          }
288        }
289        else
290        {
291          for ( int i = 0; i<networkSockets.size(); i++)
292          {
293            if ( networkSockets[i] != NULL )
294            {
295              PRINTF(5)("write %d bytes to socket %d\n", dataLength, i);
296              networkSockets[i]->writePacket(downBuffer, dataLength);
297            }
298          }
299        }
300
301      } while( reciever!=0 );
302    }
303  }
304
305  /* UPSTREAM */
306
307  for ( int i = 0; i<networkSockets.size(); i++)
308  {
309    if ( networkSockets[i] )
310    {
311      do {
312        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
313
314        if ( dataLength<=0 )
315          continue;
316
317        header = networkProtocol->extractHeader(upBuffer, dataLength);
318        dataLength -= sizeof(header);
319
320        PRINTF(5)("read %d bytes from socket uniqueID = %d\n", dataLength, header.synchronizeableID);
321
322        if ( dataLength != header.length )
323        {
324          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
325          continue;
326        }
327
328        if ( header.synchronizeableID == 0 )
329        {
330          header.synchronizeableID = i;
331        }
332
333        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
334        {
335          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
336          {
337            if ( (*it)->writeBytes(upBuffer+sizeof(header), dataLength, i) != header.length )
338            {
339              PRINTF(1)("%s did not read all the data id = %d!\n", (*it)->getClassName(), (*it)->getUniqueID());
340              break;
341            }
342            continue;
343          }
344        }
345
346      } while ( dataLength>0 );
347    }
348  }
349}
350
351void NetworkStream::updateConnectionList( )
352{
353  //check for new connections
354
355  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
356
357  if ( tempNetworkSocket )
358  {
359    int clientId;
360    if ( freeSocketSlots.size() >0 )
361    {
362      clientId = freeSocketSlots.back();
363      freeSocketSlots.pop_back();
364      networkSockets[clientId] = tempNetworkSocket;
365      handshakes[clientId] = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
366      handshakes[clientId]->setUniqueID(clientId);
367    } else
368    {
369      clientId = networkSockets.size();
370      networkSockets.push_back(tempNetworkSocket);
371      Handshake* tHs = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
372      tHs->setUniqueID(clientId);
373      handshakes.push_back(tHs);
374    }
375
376    if ( clientId > this->maxConnections )
377    {
378      handshakes[clientId]->doReject();
379      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
380    }
381    else
382
383    PRINTF(0)("New Client: %d\n", clientId);
384
385    //this->connectSynchronizeable(*handshakes[clientId]);
386  }
387
388
389  //check if connections are ok else remove them
390  for ( int i = 1; i<networkSockets.size(); i++)
391  {
392    if ( networkSockets[i] && !networkSockets[i]->isOk() )
393    {
394      //TODO: tell EntityManager that this player left the game
395      PRINTF(0)("Client is gone: %d\n", i);
396
397      //delete networkSockets[i];
398      networkSockets[i]->disconnectServer();
399      networkSockets[i]->destroy();
400      networkSockets[i] = NULL;
401
402      if ( handshakes[i] )
403        delete handshakes[i];
404      handshakes[i] = NULL;
405
406
407      NetworkGameManager::getInstance()->signalLeftPlayer(i);
408
409      if ( i == networkSockets.size()-1 )
410      {
411        networkSockets.pop_back();
412        handshakes.pop_back();
413      }
414      else
415      {
416        freeSocketSlots.push_back(i);
417      }
418    }
419  }
420
421
422}
423
424void NetworkStream::setMaxConnections( int n )
425{
426  if ( !this->isServer() )
427  {
428    PRINTF(1)("Cannot set maxConnections because I am no server.\n");
429  }
430  if ( this->networkSockets.size() > 1 )
431  {
432    PRINTF(1)("Cannot set maxConnections because there are already %d connections.\n", this->networkSockets.size());
433    return;
434  }
435
436  if ( n > MAX_CONNECTIONS )
437  {
438    PRINTF(1)("Cannot set maxConnectiosn to %d because of hardcoded limit %d\n", n, MAX_CONNECTIONS);
439    return;
440  }
441
442  this->maxConnections = n;
443  this->networkGameManager->setUniqueID( n+2 );
444}
445
446
447
448void NetworkStream::debug()
449{
450  if( this->isServer())
451    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
452  else
453    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
454
455  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
456  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
457  {
458    if( (*it)->beSynchronized() == true)
459      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
460               (*it)->getUniqueID(), (*it)->beSynchronized());
461  }
462  PRINT(0)(" Maximal Connections: %i\n", this->maxConnections);
463
464}
465
466
467int NetworkStream::getSyncCount()
468{
469  int n = 0;
470  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
471    if( (*it)->beSynchronized() == true)
472      ++n;
473
474  //return synchronizeables.size();
475  return n;
476}
477
478
479
480
481
482
Note: See TracBrowser for help on using the repository browser.