Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

network_socket: uses now a thread to send

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