Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6326 was 6326, checked in by rennerc, 18 years ago
File size: 10.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 "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            (*it)->writeBytes(upBuffer+sizeof(header), dataLength, i);
306        }
307
308      } while ( dataLength>0 );
309    }
310  }
311}
312
313void NetworkStream::updateConnectionList( )
314{
315  //check for new connections
316
317  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
318
319  if ( tempNetworkSocket )
320  {
321    int clientId;
322    if ( freeSocketSlots.size() >0 )
323    {
324      clientId = freeSocketSlots.back();
325      freeSocketSlots.pop_back();
326      networkSockets[clientId] = tempNetworkSocket;
327      handshakes[clientId] = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
328      handshakes[clientId]->setUniqueID(clientId);
329    } else
330    {
331      clientId = networkSockets.size();
332      networkSockets.push_back(tempNetworkSocket);
333      Handshake* tHs = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
334      tHs->setUniqueID(clientId);
335      handshakes.push_back(tHs);
336    }
337
338    if ( clientId > this->maxConnections )
339    {
340      handshakes[clientId]->doReject();
341      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
342    }
343    else
344
345    PRINTF(0)("New Client: %d\n", clientId);
346
347    this->connectSynchronizeable(*handshakes[clientId]);
348  }
349
350
351  //check if connections are ok else remove them
352  for ( int i = 1; i<networkSockets.size(); i++)
353  {
354    if ( networkSockets[i] && !networkSockets[i]->isOk() )
355    {
356      //TODO: tell EntityManager that this player left the game
357      PRINTF(0)("Client is gone: %d\n", i);
358
359      //delete networkSockets[i];
360      networkSockets[i]->disconnectServer();
361      networkSockets[i]->destroy();
362      networkSockets[i] = NULL;
363      //TODO: delete handshake from synchronizeable list so i can delete it
364      if ( handshakes[i] )
365        delete handshakes[i];
366      handshakes[i] = NULL;
367
368      if ( i == networkSockets.size()-1 )
369      {
370        networkSockets.pop_back();
371        handshakes.pop_back();
372      }
373      else
374      {
375        freeSocketSlots.push_back(i);
376      }
377    }
378  }
379
380
381}
382
383void NetworkStream::setMaxConnections( int n )
384{
385  if ( !this->isServer() )
386  {
387    PRINTF(1)("Cannot set maxConnections because I am no server.\n");
388  }
389  if ( this->networkSockets.size() > 1 )
390  {
391    PRINTF(1)("Cannot set maxConnections because there are already %d connections.\n", this->networkSockets.size());
392    return;
393  }
394
395  if ( n > MAX_CONNECTIONS )
396  {
397    PRINTF(1)("Cannot set maxConnectiosn to %d because of hardcoded limit %d\n", n, MAX_CONNECTIONS);
398    return;
399  }
400
401  this->maxConnections = n;
402  this->networkGameManager->setUniqueID( n+2 );
403}
404
405
Note: See TracBrowser for help on using the repository browser.