Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/network_socket.cc @ 7626

Last change on this file since 7626 was 7440, checked in by bensch, 19 years ago

orxonox/trunk: merged the Signal-Handler-Branche back to the TRUNK

File size: 10.6 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: Christoph Renner, David Hasenfratz
13   co-programmer:
14*/
15
16
17
18/* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
19   For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
20*/
21#define DEBUG_MODULE_NETWORK
22
23#include "converter.h"
24
25/* include your own header */
26#include "network_socket.h"
27
28/* header for debug output */
29#include "debug.h"
30
31/**
32 * Default constructor
33 */
34NetworkSocket::NetworkSocket()
35{
36  this->init();
37}
38
39/**
40 * Constructor to connect directly
41 */
42NetworkSocket::NetworkSocket(IPaddress ip)
43{
44  this->init();
45  connectToServer(ip);
46}
47
48
49NetworkSocket::NetworkSocket( TCPsocket sock )
50{
51  this->init();
52  this->tcpSocket = sock;
53
54  readThread = SDL_CreateThread(thread_read, (void*)this);
55  writeThread = SDL_CreateThread(thread_write, (void*)this);
56}
57
58void NetworkSocket::init()
59{
60  /* set the class id for the base object */
61  this->setClassID(CL_NETWORK_SOCKET, "NetworkSocket");
62
63  tcpSocket = NULL;
64  incomingBufferLength = 0;
65  outgoingBufferLength = 0;
66
67  readThread = NULL;
68  writeThread = NULL;
69
70
71  thread_write_running = false;
72  thread_read_running = false;
73
74  incomingBufferMutex = SDL_CreateMutex();
75  outgoingBufferMutex = SDL_CreateMutex();
76
77
78  socketMutex = SDL_CreateMutex();
79  terminateThread = false;
80
81  /* Init SDL_net */
82  //NOTE: do we need to call SDLNet_Init for all instances?
83  if(SDLNet_Init()==-1)
84  {
85    PRINTF(1)("SDLNet_Init: %s\n", SDLNet_GetError());
86    return;
87  }
88  else
89    PRINTF(5)("SDL_net initialized\n");
90
91  PRINTF(0)("NetworkSocket created\n");
92
93}
94
95
96
97/**
98 * Default destructor
99 * dont use this from outside: use destroy() instead!!
100 */
101NetworkSocket::~NetworkSocket( )
102{
103  this->terminateThread = true;
104  /* Quit SDL_net */
105  // NOTE: what if other instances of NetworkSocket running?
106  SDLNet_Quit();
107  PRINTF(5)("SDL_net shutdown\n");
108
109  SDL_DestroyMutex(incomingBufferMutex);
110  SDL_DestroyMutex(outgoingBufferMutex);
111  SDL_DestroyMutex(socketMutex);
112  SDL_DestroyMutex(threadTerminationMutex);
113}
114
115/**
116 * This function establishes a TCP/UDP connection to a given server (function argument).
117 * It is called by the NetworkStream. It creates a TCP/UDP socket for the connection.
118 * @param ip
119 */
120void NetworkSocket::connectToServer(IPaddress ip)
121{
122  //HACK this will cause segfault
123#warning remove this
124  int * a;
125  *a = 99;
126  //check if not already connected or listening
127  if (tcpSocket)
128  {
129    PRINTF(1)("NetworkSocket::listen: tcpSocket!=NULL! maybe you already called listen or connectToServer or did not call disconnectServer()!");
130  }
131
132  /* Connect to the host and port contained in ip using a TCP connection. */
133  tcpSocket = SDLNet_TCP_Open(&ip);
134  if(!tcpSocket)
135  {
136    PRINTF(1)("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
137    return;
138  }
139
140  readThread = SDL_CreateThread(thread_read, (void*)this);
141  writeThread = SDL_CreateThread(thread_write, (void*)this);
142}
143
144
145/**
146 * DTears down a TCP/UDP connection.
147 */
148void NetworkSocket::disconnectServer( )
149{
150  terminateThread = true;
151  /* Close the connection */
152
153  SDL_mutexP(socketMutex);
154  SDLNet_TCP_Close(tcpSocket);
155  tcpSocket = NULL;
156  SDL_mutexV(socketMutex);
157}
158
159
160/**
161 * This function writes some bytes (data) to the network connection (if the connection is already
162 * estabilhed) otherwise it just does nothing (silently discarding the data). And writes some
163 * warnings
164 * @param data: pointer to the data to send
165 * @param length: n bytes to send
166 * @return the number successfully written bytes
167 */
168int NetworkSocket::writeBytes(byte * data, int length)
169{
170  PRINTF(5)("NetworkSocket::writeBytes()\n");
171#ifdef _USE_OUTGOING_BUFFER
172
173#define min(a,b) (a<b)?a:b
174  int nbytes = min(_OUTGOING_BUFFER_SIZE - outgoingBufferLength, length);
175#undef min
176
177  if (!tcpSocket || data==NULL || nbytes<=0)
178  {
179    assert(_OUTGOING_BUFFER_SIZE - outgoingBufferLength > 0);
180    return 0;
181  }
182
183  SDL_mutexP(outgoingBufferMutex);
184
185  memcpy(outgoingBuffer + outgoingBufferLength, data, nbytes);
186  outgoingBufferLength += nbytes;
187
188  SDL_mutexV(outgoingBufferMutex);
189
190
191  return nbytes;
192#else
193  SDL_mutexP(socketMutex);
194
195  if (!tcpSocket || data==NULL)
196    return 0;
197
198  int res = SDLNet_TCP_Send(tcpSocket, data, length);
199
200  SDL_mutexV(socketMutex);
201
202  if (res<length)
203    PRINTF(1)("SDLNet_TCP_Send: %s\n", SDLNet_GetError());
204
205  return res;
206#endif
207}
208
209/**
210 * Reads in the bytes from the network interface and passes it to the NetworkStream.
211 * This function must internaly be implemented/connected as a thread, since the read
212 * functions of many network libraries are blocking an would therefore block the whole
213 * program.
214 * From outside, the thread shouldn't be accessible at all.
215 * @param data: pointer to memory, big enough to store length bytes
216 * @param length: n bytes to read
217 * @return the number successfully read bytes. -1 on error. may be less than length!
218 */
219int NetworkSocket::readBytes(byte * data, int length)
220{
221  PRINTF(5)("NetworkSocket::readBytes()\n");
222  if (data==NULL)
223    return 0;
224
225  int nbytes = (length<incomingBufferLength) ? length : incomingBufferLength;
226
227
228  //printf("readBytes: nbytes = %d; length=%d; incomingBufferLength=%d\n", nbytes, length, incomingBufferLength);
229
230  // just in case ...
231  if (nbytes<0)
232    return -1;
233
234  if (nbytes==0)
235      return 0;
236
237  SDL_mutexP(incomingBufferMutex);
238
239  memcpy(data, incomingBuffer, nbytes);
240
241  //important: use memmove because the memory areas may overlap
242  memmove(incomingBuffer, incomingBuffer+nbytes, incomingBufferLength-nbytes);
243  incomingBufferLength -= nbytes;
244
245  SDL_mutexV(incomingBufferMutex);
246
247  return nbytes;
248}
249
250/**
251 * Reads in the bytes form the network interface and passes it to the NetworkStream.
252 * It only reads the bytes if there are enough bytes in our buffer.
253 * @param data: pointer to memory, big enough to store length bytes
254 * @param length: n bytes to read
255 * @return the number successfully read bytes. -1 on error. 0 if there are not enough bytes in our buffer.
256 */
257int NetworkSocket::readBlock(byte * data, int length)
258{
259  printf("NetworkSocket: got %i bytes, NetworkStream requested %i bytes\n", this->incomingBufferLength, length);
260  if (incomingBufferLength >= length)
261    return readBytes(data, length);
262  else return 0;
263}
264
265
266/**
267 * used to create a thread to read from socket
268 * @param data: pointer to NetworkSocket
269 */
270int NetworkSocket::thread_read( void * data )
271{
272  int nbytesread = 0;
273  int nbytestoread = 0;
274  char buffer[_LOCAL_BUFFER_SIZE];
275  NetworkSocket * self = (NetworkSocket*)data;
276
277  self->thread_read_running = true;
278
279  while (!self->terminateThread)
280  {
281#define min(a,b) (a<b)?a:b
282    nbytestoread = min(_INCOMING_BUFFER_SIZE - self->incomingBufferLength, _LOCAL_BUFFER_SIZE);
283#undef min
284
285    //if buffer is full
286    if (nbytestoread<=0 || !self->tcpSocket)
287    {
288      SDL_Delay(_MSECONDS_SLEEP_FULL_BUFFER);
289      continue;
290    }
291
292    nbytesread = SDLNet_TCP_Recv(self->tcpSocket, buffer, nbytestoread);
293
294    SDL_mutexP(self->incomingBufferMutex);
295
296    if (nbytesread<=0)
297    {
298      if (nbytesread<0)
299        printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
300
301      SDL_mutexP(self->socketMutex);
302
303      SDLNet_TCP_Close(self->tcpSocket);
304      self->tcpSocket = NULL;
305
306      SDL_mutexV(self->socketMutex);
307      SDL_mutexV(self->incomingBufferMutex);
308      continue;
309    }
310
311    //printf("thread_read: nbytesread=%d\n", nbytesread);
312
313    memcpy(self->incomingBuffer+self->incomingBufferLength, buffer, nbytesread);
314    self->incomingBufferLength += nbytesread;
315
316    SDL_mutexV(self->incomingBufferMutex);
317  }
318
319  SDL_mutexP(self->threadTerminationMutex);
320  self->thread_read_running = false;
321
322  if ( !self->thread_write_running )
323  {
324    //delete self;
325    SDL_mutexV(self->threadTerminationMutex);
326  }
327  else
328  {
329    SDL_mutexV(self->threadTerminationMutex);
330  }
331
332
333#ifdef DONTEXITTHREADS
334  while ( true )
335  {
336    SDL_Delay(1000);
337  }
338#endif
339 
340  PRINTF(0)("QUIT READ THREAD\n");
341 
342  return 0;
343}
344
345int NetworkSocket::thread_write( void * data )
346{
347  int nbyteswrite = 0;
348  int nbytestowrite = 0;
349  char buffer[_LOCAL_BUFFER_SIZE];
350  NetworkSocket * self = (NetworkSocket*)data;
351
352  self->thread_write_running = true;
353
354  while (!self->terminateThread)
355  {
356#define min(a,b) (a<b)?a:b
357    nbytestowrite = min(self->outgoingBufferLength, _LOCAL_BUFFER_SIZE);
358#undef min
359
360//     printf("thread_write nbytes=%d listening=%d\n", nbytestowrite, (int)self->_isListening);
361
362    //if buffer is full
363    if (nbytestowrite<=0 || !self->tcpSocket)
364    {
365      SDL_Delay(_MSECONDS_SLEEP_EMPTY_BUFFER);
366      continue;
367    }
368
369    SDL_mutexP(self->outgoingBufferMutex);
370
371    //printf("a\n");
372
373    memcpy(buffer, self->outgoingBuffer, nbytestowrite);
374    self->outgoingBufferLength -= nbytestowrite;
375    memmove(self->outgoingBuffer, self->outgoingBuffer+nbytestowrite, self->outgoingBufferLength);
376
377    SDL_mutexV(self->outgoingBufferMutex);
378
379    nbyteswrite = SDLNet_TCP_Send(self->tcpSocket, buffer, nbytestowrite);
380
381    if (nbyteswrite<=0)
382    {
383      printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
384
385      SDL_mutexP(self->socketMutex);
386
387      SDLNet_TCP_Close(self->tcpSocket);
388      self->tcpSocket = NULL;
389
390      SDL_mutexV(self->socketMutex);
391      continue;
392    }
393
394  }
395
396  SDL_mutexP(self->threadTerminationMutex);
397  self->thread_write_running = false;
398
399  if ( !self->thread_read_running )
400  {
401    //delete self;
402    SDL_mutexV(self->threadTerminationMutex);
403  }
404  else
405  {
406    SDL_mutexV(self->threadTerminationMutex);
407  }
408
409#ifdef DONTEXITTHREADS
410  while ( true )
411  {
412  SDL_Delay(1000);
413  }
414#endif
415
416  PRINTF(0)("QUIT WRITE THREAD\n");
417
418  return 0;
419 
420}
421
422bool NetworkSocket::writePacket( byte * data, int length )
423{
424  PRINTF(5)("NetworkSocket::writePacket() size=%d\n", length);
425
426  if ( length > 1024 )
427  PRINTF(2)("WARNING SENDING BIG PACKET SIZE = %d\n", length);
428
429  byte blen[INTSIZE];
430
431  Converter::intToByteArray( length, blen, INTSIZE );
432
433  writeBytes(blen, INTSIZE);
434  writeBytes(data, length);
435}
436
437int NetworkSocket::readPacket( byte * data, int maxLength )
438{
439  PRINTF(5)("NetworkSocket::readPacket()\n");
440  if (incomingBufferLength<INTSIZE)
441  {
442    return 0;
443  }
444
445  int blen;
446  Converter::byteArrayToInt( incomingBuffer, &blen );
447
448  if (blen>maxLength)
449  {
450    PRINTF(1)("Buffersize is too small (%d) for packet (%d).\n", maxLength, blen);
451    assert(false);
452    return 0;
453  }
454
455  if (blen>incomingBufferLength)
456  {
457    return 0;
458  }
459
460  byte t[INTSIZE];
461  readBytes(t, INTSIZE);
462  int res = readBytes(data, blen);
463
464  if (res!=blen)
465    return -1;
466  else
467    return blen;
468
469}
470
471
Note: See TracBrowser for help on using the repository browser.