Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

implemented udp sockets

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