Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6193 was 6144, checked in by bensch, 19 years ago

orxonox/trunk: minor fix in synchronizeable erase instead of remove

File size: 9.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 "debug.h"
30#include "class_list.h"
31#include <algorithm>
32
33/* include your own header */
34#include "network_stream.h"
35
36/* probably unnecessary */
37using namespace std;
38
39
40#define PACKAGE_SIZE  256
41
42
43NetworkStream::NetworkStream()
44    : DataStream()
45{
46  this->init();
47  /* initialize the references */
48  this->type = NET_CLIENT;
49  this->networkProtocol = new NetworkProtocol();
50  this->connectionMonitor = new ConnectionMonitor();
51}
52
53NetworkStream::NetworkStream(IPaddress& address)
54{
55  this->type = NET_CLIENT;
56  this->init();
57  this->networkSockets.push_back(new NetworkSocket(address));
58  this->networkProtocol = new NetworkProtocol();
59  this->connectionMonitor = new ConnectionMonitor();
60
61  Handshake* hs = new Handshake(false);
62  hs->setUniqueID( 0 );
63  this->handshakes.push_back(hs);
64  this->connectSynchronizeable(*hs);
65  PRINTF(0)("NetworkStream: %s\n", hs->getName());
66}
67
68
69NetworkStream::NetworkStream(unsigned int port)
70{
71  this->type = NET_SERVER;
72  this->init();
73  this->serverSocket = new ServerSocket(port);
74  this->networkProtocol = new NetworkProtocol();
75  this->connectionMonitor = new ConnectionMonitor();
76  this->networkSockets.push_back( NULL );
77  this->handshakes.push_back( NULL );
78  this->bActive = true;
79
80  this->setMaxConnections( 10 );
81}
82
83
84void NetworkStream::init()
85{
86  /* set the class id for the base object */
87  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
88  this->bActive = false;
89  this->serverSocket = NULL;
90  myHostId = 0;
91}
92
93
94NetworkStream::~NetworkStream()
95{
96  if ( this->serverSocket )
97  {
98    serverSocket->close();
99    delete serverSocket;
100  }
101
102  for (NetworkSocketVector::iterator i = networkSockets.begin(); i!=networkSockets.end(); i++)
103  {
104    if ( *i )
105    {
106      (*i)->disconnectServer();
107      (*i)->destroy();
108    }
109  }
110
111  for (HandshakeVector::iterator i = handshakes.begin(); i!=handshakes.end(); i++)
112  {
113    if ( *i )
114    {
115      delete (*i);
116    }
117  }
118
119  delete connectionMonitor;
120  delete networkProtocol;
121}
122
123
124void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
125{
126  this->synchronizeables.push_back(&sync);
127  sync.setNetworkStream( this );
128
129  if( this->networkSockets.size()>0 )
130    this->bActive = true;
131}
132
133void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
134{
135  // removing the Synchronizeable from the List.
136  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
137  if (disconnectSynchro != this->synchronizeables.end())
138    this->synchronizeables.erase(disconnectSynchro);
139
140  if( this->networkSockets.size()<=0 )
141    this->bActive = false;
142}
143
144
145void NetworkStream::processData()
146{
147  if ( this->type == NET_SERVER )
148    this->updateConnectionList();
149  else
150  {
151    if ( networkSockets[0] && !networkSockets[0]->isOk() )
152    {
153      PRINTF(1)("lost connection to server\n");
154
155      //delete networkSockets[i];
156      networkSockets[0]->disconnectServer();
157      networkSockets[0]->destroy();
158      networkSockets[0] = NULL;
159      //TODO: delete handshake from synchronizeable list so i can delete it
160      if ( handshakes[0] )
161        delete handshakes[0];
162      handshakes[0] = NULL;
163    }
164  }
165
166  for (int i = 0; i<handshakes.size(); i++)
167  {
168    if ( handshakes[i] )
169    {
170      if ( handshakes[i]->completed() )
171      {
172        if ( handshakes[i]->ok() )
173        {
174          if ( type != NET_SERVER )
175          {
176            NetworkManager::getInstance()->setHostID( handshakes[i]->getHostId() );
177            myHostId = NetworkManager::getInstance()->getHostID();
178          }
179          PRINT(0)("handshake finished\n");
180          delete handshakes[i];
181          handshakes[i] = NULL;
182          //TODO: replace handshake by entitymanager
183        }
184        else
185        {
186          PRINT(1)("handshake failed!\n");
187          networkSockets[i]->disconnectServer();
188          delete handshakes[i];
189          handshakes[i] = NULL;
190          //TODO: handle error
191        }
192      }
193    }
194  }
195
196
197  /* DOWNSTREAM */
198
199  int dataLength;
200  int reciever;
201  Header header;
202  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
203  {
204    //TODO: remove items from synchronizeables if they dont exist
205    if ( (*it)!=NULL && (*it)->getOwner() == myHostId )
206    {
207      do {
208        reciever = 0;
209        dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
210
211
212        if ( dataLength<=0 ){
213          reciever = 0;
214          continue;
215        }
216
217        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
218
219        //FIXME: this is a hack, find a better way
220        Header* header = (Header*)downBuffer;
221        if ( header->synchronizeableID<100 )
222          header->synchronizeableID = 0;
223
224        if ( dataLength<=0 )
225          continue;
226
227        if ( reciever!=0 )
228        {
229          if ( networkSockets[reciever] != NULL )
230          {
231            PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
232            networkSockets[reciever]->writePacket(downBuffer, dataLength);
233          }
234          else
235          {
236            PRINTF(1)("networkSockets[reciever] == NULL\n");
237          }
238        }
239        else
240        {
241          for ( int i = 0; i<networkSockets.size(); i++)
242          {
243            if ( networkSockets[i] != NULL )
244            {
245              PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
246              networkSockets[i]->writePacket(downBuffer, dataLength);
247            }
248          }
249        }
250
251      } while( reciever!=0 );
252    }
253    else
254    {
255      PRINTF(0)("synchronizeables == NULL");
256    }
257  }
258
259  /* UPSTREAM */
260
261  for ( int i = 0; i<networkSockets.size(); i++)
262  {
263    if ( networkSockets[i] )
264    {
265      do {
266        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
267
268        if ( dataLength<=0 )
269          continue;
270
271        PRINTF(5)("read %d bytes from socket\n", dataLength);
272        header = networkProtocol->extractHeader(upBuffer, dataLength);
273        dataLength -= sizeof(header);
274
275        if ( dataLength != header.length )
276        {
277          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
278          continue;
279        }
280
281        if ( header.synchronizeableID == 0 )
282        {
283          header.synchronizeableID = i;
284        }
285
286        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
287        {
288          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
289            (*it)->writeBytes(upBuffer+sizeof(header), dataLength);
290        }
291
292      } while ( dataLength>0 );
293    }
294  }
295}
296
297void NetworkStream::updateConnectionList( )
298{
299  //check for new connections
300
301  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
302
303  if ( tempNetworkSocket )
304  {
305    int clientId;
306    if ( freeSocketSlots.size() >0 )
307    {
308      clientId = freeSocketSlots.back();
309      freeSocketSlots.pop_back();
310      networkSockets[clientId] = tempNetworkSocket;
311      handshakes[clientId] = new Handshake(true, clientId);
312      handshakes[clientId]->setUniqueID(clientId);
313    } else
314    {
315      clientId = networkSockets.size();
316      networkSockets.push_back(tempNetworkSocket);
317      Handshake* tHs = new Handshake(true, clientId);
318      tHs->setUniqueID(clientId);
319      handshakes.push_back(tHs);
320    }
321
322    if ( clientId > this->maxConnections )
323    {
324      handshakes[clientId]->doReject();
325      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
326    }
327    else
328
329    PRINTF(0)("New Client: %d\n", clientId);
330
331    this->connectSynchronizeable(*handshakes[clientId]);
332  }
333
334
335  //check if connections are ok else remove them
336  for ( int i = 1; i<networkSockets.size(); i++)
337  {
338    if ( networkSockets[i] && !networkSockets[i]->isOk() )
339    {
340      //TODO: tell EntityManager that this player left the game
341      PRINTF(0)("Client is gone: %d\n", i);
342
343      //delete networkSockets[i];
344      networkSockets[i]->disconnectServer();
345      networkSockets[i]->destroy();
346      networkSockets[i] = NULL;
347      //TODO: delete handshake from synchronizeable list so i can delete it
348      if ( handshakes[i] )
349        delete handshakes[i];
350      handshakes[i] = NULL;
351
352      if ( i == networkSockets.size()-1 )
353      {
354        networkSockets.pop_back();
355        handshakes.pop_back();
356      }
357      else
358      {
359        freeSocketSlots.push_back(i);
360      }
361    }
362  }
363
364
365}
366
367void NetworkStream::setMaxConnections( int n )
368{
369  if ( !this->isServer() )
370  {
371    PRINTF(1)("Cannot set maxConnections because I am no server.\n");
372  }
373  if ( this->networkSockets.size() > 1 )
374  {
375    PRINTF(1)("Cannot set maxConnections because there are already %d connections.\n", this->networkSockets.size());
376    return;
377  }
378  this->maxConnections = n;
379}
380
381
Note: See TracBrowser for help on using the repository browser.