Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6061 was 6060, checked in by bwuest, 18 years ago

Network changes

File size: 10.1 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
125  if( this->networkSockets.size()>0 )
126    this->bActive = true;
127}
128
129void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
130{
131  this->synchronizeables.remove(&sync);
132
133  if( this->networkSockets.size()<=0 )
134    this->bActive = false;
135}
136
137
138void NetworkStream::processData()
139{
140  if ( this->type == NET_SERVER )
141    this->updateConnectionList();
142
143  for (int i = 0; i<handshakes.size(); i++)
144  {
145    if ( handshakes[i] )
146    {
147      if ( handshakes[i]->completed() )
148      {
149        if ( handshakes[i]->ok() )
150        {
151          if ( type != NET_SERVER )
152          {
153            NetworkManager::getInstance()->setHostID( handshakes[i]->getHostId() );
154            myHostId = NetworkManager::getInstance()->getHostID();
155          }
156          PRINT(0)("handshake finished\n");
157          //TODO: replace handshake by entitymanager
158        }
159        else
160        {
161          PRINT(1)("handshake failed!\n");
162          networkSockets[i]->disconnectServer();
163          //TODO: handle error
164        }
165      }
166    }
167  }
168
169
170  /* DOWNSTREAM */
171
172  int dataLength;
173  int reciever;
174  Header header;
175  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
176  {
177    //TODO: remove items from synchronizeables if they dont exist
178    if ( (*it)!=NULL  && ClassList::exists(*it) && (*it)->getOwner() == myHostId )
179    {
180      do {
181        reciever = 0;
182        dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
183
184
185        if ( dataLength<=0 ){
186          reciever = 0;
187          continue;
188        }
189
190        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
191
192        if ( dataLength<=0 )
193          continue;
194
195        if ( reciever!=0 )
196        {
197          if ( networkSockets[reciever] != NULL )
198          {
199            PRINTF(0)("write %d bytes to socket %d\n", dataLength, reciever);
200            networkSockets[reciever]->writePacket(downBuffer, dataLength);
201          }
202          else
203          {
204            PRINTF(1)("networkSockets[reciever] == NULL\n");
205          }
206        }
207        else
208        {
209          for ( int i = 0; i<networkSockets.size(); i++)
210          {
211            if ( networkSockets[i] != NULL )
212            {
213              PRINTF(0)("write %d bytes to socket %d\n", dataLength, reciever);
214              networkSockets[i]->writePacket(downBuffer, dataLength);
215            }
216          }
217        }
218
219      } while( reciever!=0 );
220    }
221    else
222    {
223      PRINTF(0)("synchronizeables == NULL");
224    }
225  }
226
227  /* UPSTREAM */
228
229  for ( int i = 0; i<networkSockets.size(); i++)
230  {
231    if ( networkSockets[i] )
232    {
233      do {
234        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
235
236        if ( dataLength<=0 )
237          continue;
238
239        PRINTF(0)("read %d bytes from socket\n", dataLength);
240        header = networkProtocol->extractHeader(upBuffer, dataLength);
241        dataLength -= sizeof(header);
242
243        if ( dataLength != header.length )
244        {
245          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
246          continue;
247        }
248
249        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
250        {
251          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
252            (*it)->writeBytes(upBuffer+sizeof(header), dataLength);
253        }
254
255      } while ( dataLength>0 );
256    }
257  }
258
259#if 0
260  int dataLength = 0;
261
262  /* DOWNSTREAM */
263  printf("\nSynchronizeable: %s\n", this->synchronizeables->getName());
264  PRINT(0)("============= DOWNSTREAM:===============\n");
265  /* first of all read the synchronizeable's data: */
266  if( this->isServer())
267    dataLength = this->synchronizeables->readBytes((byte*)downBuffer);
268
269  if( dataLength > 0)
270  {
271    /* send the received data to connectionMonitor */
272    this->connectionMonitor->processPacket((byte*)downBuffer, dataLength);
273
274    dataLength = this->networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE,
275                 *(this->synchronizeables), 12/* some random number (no real id)*/);
276
277    /* pass the data to the network socket */
278 //   dataLength = this->networkSocket->writeBytes((byte*)downBuffer, dataLength);
279    /* check if there was an error */
280    if( dataLength == -1)
281    {
282      PRINTF(0)("Error in writing data to the NetworkSocket\n");
283    }
284  }
285
286
287  /* UPSTREAM */
288  dataLength = 0;
289  PRINT(0)("============== UPSTREAM:================\n");
290  /* first of all read the next Orxonox Network Header */
291
292  if( this->state == NET_REC_HEADER)
293  {
294//    dataLength = this->networkSocket->readBlock((byte*)upBuffer, sizeof(Header));
295    if( dataLength == sizeof(Header))
296    {
297      this->packetHeader = this->networkProtocol->extractHeader((byte*) upBuffer , dataLength);
298      printf("NetworkStream::processData() - Got Header: Protocol %u, Version: %u, Sender: %u, Receiver: %u, Length: %u\n",
299             this->packetHeader.protocol, this->packetHeader.version, this->packetHeader.senderID,
300             this->packetHeader.receiverID, this->packetHeader.length);
301      /* FIXME: what if it was no this->packetHeader? catch? eg: the protocol identifier, receiver id*/
302
303      this->state = NET_REC_DATA;
304    }
305  }
306  if( this->state == NET_REC_DATA)
307  {
308    /* now read the data */
309//    dataLength = this->networkSocket->readBlock((byte*)upBuffer, this->packetHeader.length);
310    /* check if the data is available and process it if so */
311    if( dataLength == this->packetHeader.length)
312    {
313      printf("NetworkStream::processData() - Got Data: %i bytes\n", dataLength);
314      /* send the received data to connectionMonitor */
315      this->connectionMonitor->processPacket((byte*)upBuffer, this->packetHeader.length);
316      /* now pass the data to the sync object */
317      if( !this->isServer())
318        this->synchronizeables->writeBytes((byte*)upBuffer, this->packetHeader.length);
319
320      this->state = NET_REC_HEADER;
321    }
322  }
323
324#endif
325}
326
327void NetworkStream::updateConnectionList( )
328{
329  //check for new connections
330
331  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
332
333  if ( tempNetworkSocket )
334  {
335    int clientId;
336    if ( freeSocketSlots.size() >0 )
337    {
338      clientId = freeSocketSlots.back();
339      freeSocketSlots.pop_back();
340      networkSockets[clientId] = tempNetworkSocket;
341      handshakes[clientId] = new Handshake(true, clientId);
342    } else
343    {
344      clientId = networkSockets.size();
345      networkSockets.push_back(tempNetworkSocket);
346      handshakes.push_back(new Handshake(true, clientId));
347    }
348
349    PRINTF(0)("New Client: %d\n", clientId);
350
351    this->connectSynchronizeable(*handshakes[clientId]);
352  }
353
354
355  //check if connections are ok else remove them
356  for ( int i = 1; i<networkSockets.size(); i++)
357  {
358    if ( networkSockets[i] && !networkSockets[i]->isOk() )
359    {
360      //TODO: tell EntityManager that this player left the game
361      PRINTF(0)("Client is gone: %d\n", i);
362
363      //delete networkSockets[i];
364      networkSockets[i]->disconnectServer();
365      networkSockets[i]->destroy();
366      networkSockets[i] = NULL;
367      //TODO: delete handshake from synchronizeable list so i can delete it
368      delete handshakes[i];
369      handshakes[i] = NULL;
370
371      if ( i == networkSockets.size()-1 )
372      {
373        networkSockets.pop_back();
374        handshakes.pop_back();
375      }
376      else
377      {
378        freeSocketSlots.push_back(i);
379      }
380    }
381  }
382
383
384}
385
386
Note: See TracBrowser for help on using the repository browser.