Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

network_stream: server doesnt crash on connection close :D

File size: 10.2 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 "list.h"
30#include "debug.h"
31#include "class_list.h"
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  this->handshakes.push_back(hs);
63  this->connectSynchronizeable(*hs);
64  PRINTF(0)("NetworkStream: %s\n", hs->getName());
65}
66
67
68NetworkStream::NetworkStream(unsigned int port)
69{
70  this->type = NET_SERVER;
71  this->init();
72  this->serverSocket = new ServerSocket(port);
73  this->networkProtocol = new NetworkProtocol();
74  this->connectionMonitor = new ConnectionMonitor();
75  this->networkSockets.push_back( NULL );
76  this->handshakes.push_back( NULL );
77  this->bActive = true;
78}
79
80
81void NetworkStream::init()
82{
83  /* set the class id for the base object */
84  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
85  this->bActive = false;
86  this->serverSocket = NULL;
87  myHostId = 0;
88}
89
90
91NetworkStream::~NetworkStream()
92{
93  if ( this->serverSocket )
94  {
95    serverSocket->close();
96    delete serverSocket;
97  }
98
99  for (NetworkSocketVector::iterator i = networkSockets.begin(); i!=networkSockets.end(); i++)
100  {
101    if ( *i )
102    {
103      (*i)->disconnectServer();
104      (*i)->destroy();
105    }
106  }
107
108  for (HandshakeVector::iterator i = handshakes.begin(); i!=handshakes.end(); i++)
109  {
110    if ( *i )
111    {
112      delete (*i);
113    }
114  }
115
116  delete connectionMonitor;
117  delete networkProtocol;
118}
119
120
121void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
122{
123  this->synchronizeables.push_back(&sync);
124  sync.setNetworkStream( this );
125
126  if( this->networkSockets.size()>0 )
127    this->bActive = true;
128}
129
130void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
131{
132  this->synchronizeables.remove(&sync);
133
134  if( this->networkSockets.size()<=0 )
135    this->bActive = false;
136}
137
138
139void NetworkStream::processData()
140{
141  if ( this->type == NET_SERVER )
142    this->updateConnectionList();
143
144  for (int i = 0; i<handshakes.size(); i++)
145  {
146    if ( handshakes[i] )
147    {
148      if ( handshakes[i]->completed() )
149      {
150        if ( handshakes[i]->ok() )
151        {
152          if ( type != NET_SERVER )
153          {
154            NetworkManager::getInstance()->setHostID( handshakes[i]->getHostId() );
155            myHostId = NetworkManager::getInstance()->getHostID();
156          }
157          PRINT(0)("handshake finished\n");
158          delete handshakes[i];
159          handshakes[i] = NULL;
160          //TODO: replace handshake by entitymanager
161        }
162        else
163        {
164          PRINT(1)("handshake failed!\n");
165          networkSockets[i]->disconnectServer();
166          //TODO: handle error
167        }
168      }
169    }
170  }
171
172
173  /* DOWNSTREAM */
174
175  int dataLength;
176  int reciever;
177  Header header;
178  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
179  {
180    //TODO: remove items from synchronizeables if they dont exist
181    if ( (*it)!=NULL && (*it)->getOwner() == myHostId )
182    {
183      do {
184        reciever = 0;
185        dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
186
187
188        if ( dataLength<=0 ){
189          reciever = 0;
190          continue;
191        }
192
193        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
194
195        if ( dataLength<=0 )
196          continue;
197
198        if ( reciever!=0 )
199        {
200          if ( networkSockets[reciever] != NULL )
201          {
202            PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
203            networkSockets[reciever]->writePacket(downBuffer, dataLength);
204          }
205          else
206          {
207            PRINTF(1)("networkSockets[reciever] == NULL\n");
208          }
209        }
210        else
211        {
212          for ( int i = 0; i<networkSockets.size(); i++)
213          {
214            if ( networkSockets[i] != NULL )
215            {
216              PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
217              networkSockets[i]->writePacket(downBuffer, dataLength);
218            }
219          }
220        }
221
222      } while( reciever!=0 );
223    }
224    else
225    {
226      PRINTF(0)("synchronizeables == NULL");
227    }
228  }
229
230  /* UPSTREAM */
231
232  for ( int i = 0; i<networkSockets.size(); i++)
233  {
234    if ( networkSockets[i] )
235    {
236      do {
237        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
238
239        if ( dataLength<=0 )
240          continue;
241
242        PRINTF(0)("read %d bytes from socket\n", dataLength);
243        header = networkProtocol->extractHeader(upBuffer, dataLength);
244        dataLength -= sizeof(header);
245
246        if ( dataLength != header.length )
247        {
248          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
249          continue;
250        }
251
252        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
253        {
254          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
255            (*it)->writeBytes(upBuffer+sizeof(header), dataLength);
256        }
257
258      } while ( dataLength>0 );
259    }
260  }
261
262#if 0
263  int dataLength = 0;
264
265  /* DOWNSTREAM */
266  printf("\nSynchronizeable: %s\n", this->synchronizeables->getName());
267  PRINT(0)("============= DOWNSTREAM:===============\n");
268  /* first of all read the synchronizeable's data: */
269  if( this->isServer())
270    dataLength = this->synchronizeables->readBytes((byte*)downBuffer);
271
272  if( dataLength > 0)
273  {
274    /* send the received data to connectionMonitor */
275    this->connectionMonitor->processPacket((byte*)downBuffer, dataLength);
276
277    dataLength = this->networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE,
278                 *(this->synchronizeables), 12/* some random number (no real id)*/);
279
280    /* pass the data to the network socket */
281 //   dataLength = this->networkSocket->writeBytes((byte*)downBuffer, dataLength);
282    /* check if there was an error */
283    if( dataLength == -1)
284    {
285      PRINTF(0)("Error in writing data to the NetworkSocket\n");
286    }
287  }
288
289
290  /* UPSTREAM */
291  dataLength = 0;
292  PRINT(0)("============== UPSTREAM:================\n");
293  /* first of all read the next Orxonox Network Header */
294
295  if( this->state == NET_REC_HEADER)
296  {
297//    dataLength = this->networkSocket->readBlock((byte*)upBuffer, sizeof(Header));
298    if( dataLength == sizeof(Header))
299    {
300      this->packetHeader = this->networkProtocol->extractHeader((byte*) upBuffer , dataLength);
301      printf("NetworkStream::processData() - Got Header: Protocol %u, Version: %u, Sender: %u, Receiver: %u, Length: %u\n",
302             this->packetHeader.protocol, this->packetHeader.version, this->packetHeader.senderID,
303             this->packetHeader.receiverID, this->packetHeader.length);
304      /* FIXME: what if it was no this->packetHeader? catch? eg: the protocol identifier, receiver id*/
305
306      this->state = NET_REC_DATA;
307    }
308  }
309  if( this->state == NET_REC_DATA)
310  {
311    /* now read the data */
312//    dataLength = this->networkSocket->readBlock((byte*)upBuffer, this->packetHeader.length);
313    /* check if the data is available and process it if so */
314    if( dataLength == this->packetHeader.length)
315    {
316      printf("NetworkStream::processData() - Got Data: %i bytes\n", dataLength);
317      /* send the received data to connectionMonitor */
318      this->connectionMonitor->processPacket((byte*)upBuffer, this->packetHeader.length);
319      /* now pass the data to the sync object */
320      if( !this->isServer())
321        this->synchronizeables->writeBytes((byte*)upBuffer, this->packetHeader.length);
322
323      this->state = NET_REC_HEADER;
324    }
325  }
326
327#endif
328}
329
330void NetworkStream::updateConnectionList( )
331{
332  //check for new connections
333
334  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
335
336  if ( tempNetworkSocket )
337  {
338    int clientId;
339    if ( freeSocketSlots.size() >0 )
340    {
341      clientId = freeSocketSlots.back();
342      freeSocketSlots.pop_back();
343      networkSockets[clientId] = tempNetworkSocket;
344      handshakes[clientId] = new Handshake(true, clientId);
345    } else
346    {
347      clientId = networkSockets.size();
348      networkSockets.push_back(tempNetworkSocket);
349      handshakes.push_back(new Handshake(true, clientId));
350    }
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
390
Note: See TracBrowser for help on using the repository browser.