Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

network_stream: server doesnt crash on connection close :D

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