Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

handshake works now

File size: 10.0 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
129
130void NetworkStream::processData()
131{
132  PRINTF(0)("processData()\n");
133  if ( this->type == NET_SERVER )
134    this->updateConnectionList();
135
136  for (int i = 0; i<handshakes.size(); i++)
137  {
138    if ( handshakes[i] )
139    {
140      if ( handshakes[i]->completed() )
141      {
142        if ( handshakes[i]->ok() )
143        {
144          if ( type != NET_SERVER )
145          {
146            NetworkManager::getInstance()->setHostID( handshakes[i]->getHostId() );
147            myHostId = NetworkManager::getInstance()->getHostID();
148          }
149          PRINT(0)("handshake finished\n");
150        }
151        else
152        {
153          PRINT(1)("handshake failed!\n");
154          networkSockets[i]->disconnectServer();
155          //TODO: handle error
156        }
157      }
158    }
159  }
160
161
162  /* DOWNSTREAM */
163
164  int dataLength;
165  int reciever;
166  Header header;
167  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
168  {
169    if ( (*it) && (*it)->getOwner() == myHostId )
170    {
171      do {
172        reciever = 0;
173        dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
174
175        PRINTF(0)("reciever = %d\n", reciever);
176
177        if ( dataLength<=0 ){
178          reciever = 0;
179          continue;
180        }
181
182        PRINTF(0)("read %d bytes\n", dataLength);
183
184        if (ClassList::exists((*it)))
185        {
186          PRINTF(0)("before cast\n");
187          dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
188          PRINTF(0)("after cast\n");
189        }
190        else
191        {
192          PRINTF(0)("instance does not exist anymore\n");
193          //synchronizeables.remove(it);
194        }
195
196        if ( dataLength<=0 )
197          continue;
198
199        if ( reciever!=0 )
200        {
201          if ( networkSockets[reciever] )
202          {
203            PRINTF(0)("write %d bytes to socket %d\n", dataLength, reciever);
204            networkSockets[reciever]->writePacket(downBuffer, dataLength);
205          }
206          else
207          {
208            PRINTF(1)("networkSockets[reciever] == NULL\n");
209          }
210        }
211        else
212        {
213          for ( int i = 0; i<networkSockets.size(); i++)
214          {
215            if ( networkSockets[i] )
216            {
217              PRINTF(0)("write %d bytes to socket %d\n", dataLength, reciever);
218              networkSockets[i]->writePacket(downBuffer, dataLength);
219            }
220          }
221        }
222
223      } while( reciever!=0 );
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.uniqueID )
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      delete handshakes[i];
368      handshakes[i] = NULL;
369
370      if ( i == networkSockets.size()-1 )
371      {
372        networkSockets.pop_back();
373        handshakes.pop_back();
374      }
375      else
376      {
377        freeSocketSlots.push_back(i);
378      }
379    }
380  }
381
382
383}
384
385
Note: See TracBrowser for help on using the repository browser.