Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

synchronizeable: writeBytes now returns int
converter: converts now 0.0f without endless loop :D

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