Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6404 was 6341, checked in by bensch, 19 years ago

orxonox/trunk: merged the network branche back to the trunk, so we do not get away from each other to fast

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