Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/network/src/lib/network/network_socket.cc @ 6926

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

fixed a bug

File size: 10.3 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  //check if not already connected or listening
123  if (tcpSocket)
124  {
125    PRINTF(1)("NetworkSocket::listen: tcpSocket!=NULL! maybe you already called listen or connectToServer or did not call disconnectServer()!");
126  }
127
128  /* Connect to the host and port contained in ip using a TCP connection. */
129  tcpSocket = SDLNet_TCP_Open(&ip);
130  if(!tcpSocket)
131  {
132    PRINTF(1)("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
133    return;
134  }
135
136  readThread = SDL_CreateThread(thread_read, (void*)this);
137  writeThread = SDL_CreateThread(thread_write, (void*)this);
138}
139
140
141/**
142 * DTears down a TCP/UDP connection.
143 */
144void NetworkSocket::disconnectServer( )
145{
146  terminateThread = true;
147  /* Close the connection */
148
149  SDL_mutexP(socketMutex);
150  SDLNet_TCP_Close(tcpSocket);
151  tcpSocket = NULL;
152  SDL_mutexV(socketMutex);
153}
154
155
156/**
157 * This function writes some bytes (data) to the network connection (if the connection is already
158 * estabilhed) otherwise it just does nothing (silently discarding the data). And writes some
159 * warnings
160 * @param data: pointer to the data to send
161 * @param length: n bytes to send
162 * @return the number successfully written bytes
163 */
164int NetworkSocket::writeBytes(byte * data, int length)
165{
166  PRINTF(5)("NetworkSocket::writeBytes()\n");
167#ifdef _USE_OUTGOING_BUFFER
168
169#define min(a,b) (a<b)?a:b
170  int nbytes = min(_OUTGOING_BUFFER_SIZE - outgoingBufferLength, length);
171#undef min
172
173  if (!tcpSocket || data==NULL || nbytes<=0)
174  {
175    assert(false);
176    return 0;
177  }
178
179  SDL_mutexP(outgoingBufferMutex);
180
181  memcpy(outgoingBuffer + outgoingBufferLength, data, nbytes);
182  outgoingBufferLength += nbytes;
183
184  SDL_mutexV(outgoingBufferMutex);
185
186
187  return nbytes;
188#else
189  SDL_mutexP(socketMutex);
190
191  if (!tcpSocket || data==NULL)
192    return 0;
193
194  int res = SDLNet_TCP_Send(tcpSocket, data, length);
195
196  SDL_mutexV(socketMutex);
197
198  if (res<length)
199    PRINTF(1)("SDLNet_TCP_Send: %s\n", SDLNet_GetError());
200
201  return res;
202#endif
203}
204
205/**
206 * Reads in the bytes from the network interface and passes it to the NetworkStream.
207 * This function must internaly be implemented/connected as a thread, since the read
208 * functions of many network libraries are blocking an would therefore block the whole
209 * program.
210 * From outside, the thread shouldn't be accessible at all.
211 * @param data: pointer to memory, big enough to store length bytes
212 * @param length: n bytes to read
213 * @return the number successfully read bytes. -1 on error. may be less than length!
214 */
215int NetworkSocket::readBytes(byte * data, int length)
216{
217  PRINTF(5)("NetworkSocket::readBytes()\n");
218  if (data==NULL)
219    return 0;
220
221  int nbytes = (length<incomingBufferLength) ? length : incomingBufferLength;
222
223
224  //printf("readBytes: nbytes = %d; length=%d; incomingBufferLength=%d\n", nbytes, length, incomingBufferLength);
225
226  // just in case ...
227  if (nbytes<0)
228    return -1;
229
230  if (nbytes==0)
231      return 0;
232
233  SDL_mutexP(incomingBufferMutex);
234
235  memcpy(data, incomingBuffer, nbytes);
236
237  //important: use memmove because the memory areas may overlap
238  memmove(incomingBuffer, incomingBuffer+nbytes, incomingBufferLength-nbytes);
239  incomingBufferLength -= nbytes;
240
241  SDL_mutexV(incomingBufferMutex);
242
243  return nbytes;
244}
245
246/**
247 * Reads in the bytes form the network interface and passes it to the NetworkStream.
248 * It only reads the bytes if there are enough bytes in our buffer.
249 * @param data: pointer to memory, big enough to store length bytes
250 * @param length: n bytes to read
251 * @return the number successfully read bytes. -1 on error. 0 if there are not enough bytes in our buffer.
252 */
253int NetworkSocket::readBlock(byte * data, int length)
254{
255  printf("NetworkSocket: got %i bytes, NetworkStream requested %i bytes\n", this->incomingBufferLength, length);
256  if (incomingBufferLength >= length)
257    return readBytes(data, length);
258  else return 0;
259}
260
261
262/**
263 * used to create a thread to read from socket
264 * @param data: pointer to NetworkSocket
265 */
266int NetworkSocket::thread_read( void * data )
267{
268  int nbytesread = 0;
269  int nbytestoread = 0;
270  char buffer[_LOCAL_BUFFER_SIZE];
271  NetworkSocket * self = (NetworkSocket*)data;
272
273  self->thread_read_running = true;
274
275  while (!self->terminateThread)
276  {
277#define min(a,b) (a<b)?a:b
278    nbytestoread = min(_INCOMING_BUFFER_SIZE - self->incomingBufferLength, _LOCAL_BUFFER_SIZE);
279#undef min
280
281    //if buffer is full
282    if (nbytestoread<=0 || !self->tcpSocket)
283    {
284      SDL_Delay(_MSECONDS_SLEEP_FULL_BUFFER);
285      continue;
286    }
287
288    nbytesread = SDLNet_TCP_Recv(self->tcpSocket, buffer, nbytestoread);
289
290    SDL_mutexP(self->incomingBufferMutex);
291
292    if (nbytesread<=0)
293    {
294      if (nbytesread<0)
295        printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
296
297      SDL_mutexP(self->socketMutex);
298
299      SDLNet_TCP_Close(self->tcpSocket);
300      self->tcpSocket = NULL;
301
302      SDL_mutexV(self->socketMutex);
303      SDL_mutexV(self->incomingBufferMutex);
304      continue;
305    }
306
307    //printf("thread_read: nbytesread=%d\n", nbytesread);
308
309    memcpy(self->incomingBuffer+self->incomingBufferLength, buffer, nbytesread);
310    self->incomingBufferLength += nbytesread;
311
312    SDL_mutexV(self->incomingBufferMutex);
313  }
314
315  SDL_mutexP(self->threadTerminationMutex);
316  self->thread_read_running = false;
317
318  if ( !self->thread_write_running )
319  {
320    //delete self;
321    SDL_mutexV(self->threadTerminationMutex);
322  }
323  else
324  {
325    SDL_mutexV(self->threadTerminationMutex);
326  }
327
328
329  PRINTF(0)("QUIT READ THREAD\n");
330  return 0;
331}
332
333int NetworkSocket::thread_write( void * data )
334{
335  int nbyteswrite = 0;
336  int nbytestowrite = 0;
337  char buffer[_LOCAL_BUFFER_SIZE];
338  NetworkSocket * self = (NetworkSocket*)data;
339
340  self->thread_write_running = true;
341
342  while (!self->terminateThread)
343  {
344#define min(a,b) (a<b)?a:b
345    nbytestowrite = min(self->outgoingBufferLength, _LOCAL_BUFFER_SIZE);
346#undef min
347
348//     printf("thread_write nbytes=%d listening=%d\n", nbytestowrite, (int)self->_isListening);
349
350    //if buffer is full
351    if (nbytestowrite<=0 || !self->tcpSocket)
352    {
353      SDL_Delay(_MSECONDS_SLEEP_EMPTY_BUFFER);
354      continue;
355    }
356
357    SDL_mutexP(self->outgoingBufferMutex);
358
359    //printf("a\n");
360
361    memcpy(buffer, self->outgoingBuffer, nbytestowrite);
362    self->outgoingBufferLength -= nbytestowrite;
363    memmove(self->outgoingBuffer, self->outgoingBuffer+nbytestowrite, self->outgoingBufferLength);
364
365    SDL_mutexV(self->outgoingBufferMutex);
366
367    nbyteswrite = SDLNet_TCP_Send(self->tcpSocket, buffer, nbytestowrite);
368
369    if (nbyteswrite<=0)
370    {
371      printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
372
373      SDL_mutexP(self->socketMutex);
374
375      SDLNet_TCP_Close(self->tcpSocket);
376      self->tcpSocket = NULL;
377
378      SDL_mutexV(self->socketMutex);
379      continue;
380    }
381
382  }
383
384  SDL_mutexP(self->threadTerminationMutex);
385  self->thread_write_running = false;
386
387  if ( !self->thread_read_running )
388  {
389    //delete self;
390    SDL_mutexV(self->threadTerminationMutex);
391  }
392  else
393  {
394    SDL_mutexV(self->threadTerminationMutex);
395  }
396
397
398  PRINTF(0)("QUIT WRITE THREAD\n");
399  return 0;
400}
401
402bool NetworkSocket::writePacket( byte * data, int length )
403{
404  PRINTF(5)("NetworkSocket::writePacket() size=%d\n", length);
405
406  if ( length > 1024 )
407  PRINTF(2)("WARNING SENDING BIG PACKET SIZE = %d\n", length);
408
409  byte blen[INTSIZE];
410
411  Converter::intToByteArray( length, blen, INTSIZE );
412
413  writeBytes(blen, INTSIZE);
414  writeBytes(data, length);
415}
416
417int NetworkSocket::readPacket( byte * data, int maxLength )
418{
419  PRINTF(5)("NetworkSocket::readPacket()\n");
420  if (incomingBufferLength<INTSIZE)
421  {
422    return 0;
423  }
424
425  int blen;
426  Converter::byteArrayToInt( incomingBuffer, &blen );
427
428  if (blen>maxLength)
429  {
430    PRINTF(1)("Buffersize is too small (%d) for packet (%d)\n", maxLength, blen);
431    assert(false);
432    return 0;
433  }
434
435  if (blen>incomingBufferLength)
436  {
437    return 0;
438  }
439
440  byte t[INTSIZE];
441  readBytes(t, INTSIZE);
442  int res = readBytes(data, blen);
443
444  if (res!=blen)
445    return -1;
446  else
447    return blen;
448
449}
450
451
Note: See TracBrowser for help on using the repository browser.