Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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