-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.cpp
More file actions
executable file
·679 lines (562 loc) · 20 KB
/
Connection.cpp
File metadata and controls
executable file
·679 lines (562 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*
*********************************************************************************
* In the name of Almighty *
* *
* Connection.cpp : Robocup 3D Soccer Simulation Team Zigorat *
* (This team was previously named Gcyrus) *
* *
* Date: 03/20/2007 *
* Author: Mahdi Hamdarsi *
* Comments: Class definitions for TDataPorter, TConnection, TRoboCupConnection *
* utilities for network manipulation *
* *
*********************************************************************************
*/
/*! \file Connection.cpp
<pre>
<b>File:</b> Connection.cpp
<b>Project:</b> Robocup Soccer Simulation Team: Zigorat
<b>Authors:</b> Mahdi Hamdarsi
<b>Created:</b> 03/20/2007
<b>Last Revision:</b> $ID$
<b>Contents:</b> Class definitions for TDataPorter, TConnection, TRoboCupConnection
utilities for network manipulation
<hr size=2>
<h2><b>Changes</b></h2>
<b>Date</b> <b>Author</b> <b>Comment</b>
03/20/2007 Mahdi Initial version created
</pre>
*/
#include "Connection.h"
#include "Logger.h"
#include <sys/wait.h>
//#include <sys/socket.h>
//#include <sys/types.h>
//#include <sys/time.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <iostream>
//#include <netinet/tcp.h>
#define MAX_CONN_QUEUE 5 /*!< Maximum connection waiting to be listened */
using namespace std;
/********************************************************************/
/*********************** Class TDataPorter ************************/
/********************************************************************/
/*! Constructor of TDataPorter, initializes connection mode (UDP/TCP)
& creates sockets to send/recv data
\param conn ConnectionT connection mode: UDP/TCP
\param socket_fd int pre-initialized socket descriptor */
TDataPorter::TDataPorter( ConnectionT conn, int socket_fd )
{
m_SocketFD = -1;
setSocketFD( socket_fd, conn );
}
/*! Destructor of TDataPorter, closes available connections */
TDataPorter::~TDataPorter()
{
if( m_SocketFD != -1 )
close(m_SocketFD);
}
/*! This method returns connection mode: UDP/TCP
\return ConnectionT connection mode */
ConnectionT TDataPorter::getConnectionType() const
{
return m_ConnectionType;
}
/*! This methos returns socket descriptor
\return socket descriptor of current socket conenction */
int TDataPorter::getSocketFD() const
{
return m_SocketFD;
}
/*! This method sets the current socket descriptor to a pre-initialiazed
socket holder, and sets the connection mode
\param socket_fd pre-initialized socket descriptor
\param conn Connection mode: TCP/UDP
\return bool inidicating wheather class initialized or not */
bool TDataPorter::setSocketFD( int socket_fd, ConnectionT conn )
{
if( active() )
return false;
m_ConnectionType = conn;
m_SocketFD = socket_fd;
return true;
}
/*! This method sends a message through socket connection which is made
\param msg message or data to send
\param iLength length of message to send
\return int number of bytes totally sent */
int TDataPorter::sendMessage( const void * msg, int iLength ) const
{
if( !active() )
return -1;
int iRet = -1;
if( getConnectionType() == CONN_TCP )
iRet = send( m_SocketFD, msg, iLength, 0 );
else
{
cerr << "TDataPorter::sendMessage(TCP): attempted to send to a UDP packet via a TCP socket" << END;
return -1;
}
if( iRet == -1 )
perror( "TDataPorter::sendMessage" );
return iRet;
}
/*! This method sends a message through a UDP socket connection which is made
\param msg message or data to send
\param iLength length of message to send
\param remote Socket descriptor of the data porter
\return int number of bytes totally sent */
int TDataPorter::sendMessageUDP( const void * msg, int iLength, const sockaddr_in * remote ) const
{
if( !active() )
return -1;
int iRet = -1;
if( getConnectionType() == CONN_UDP )
iRet = sendto( m_SocketFD, msg, iLength, 0, (sockaddr*)remote, sizeof( *remote ) );
else
{
cerr << "TDataPorter::sendMessage(UDP): attempted to send to a TCP packet via a UDP socket" << END;
return 0;
}
if( iRet == -1 )
perror( "TDataPorter::sendMessage" );
return iRet;
}
/*! This method recieves any data which is ready in connection to read
\param msg pointer to write recieved bytes to
\param iMaxLength maximum length of bytes that can be stored in msg
\param time_out Maximum tolerable time for data to be recieved
\return int number of bytes totally recieved */
int TDataPorter::recvMessage( void * msg, int iMaxLength, int time_out ) const
{
if( !active() )
return -1;
fd_set fds;
int iReturn = waitForData( fds, time_out );
if( iReturn == -1 )
{
perror( "TDataPorter::recvMessage(select)" );
return false;
}
else if( iReturn == 0 )
{
cerr << "TDataPorter::recvMessage: Connection Timed out" << END;
return false;
}
if( FD_ISSET( getSocketFD(), &fds ) )
{
if( getConnectionType() == CONN_TCP )
iReturn = recv( getSocketFD(), msg, iMaxLength, 0);
else
{
sockaddr remote;
socklen_t from_len = sizeof( sockaddr_in );
iReturn = recvfrom( getSocketFD(), msg, iMaxLength, 0, &remote, &from_len );
}
}
else
return false;
if( iReturn == -1 )
{
perror( "TDataPorter::recvMessage" );
return false;
}
else if( iReturn == 0 )
return false;
else
( ( (char*)msg )[ iReturn ] ) = '\0';
return iReturn;
}
/*! This method writes a message to its peer
\param msg message to be written for peer
\return int number of charactors sent */
int TDataPorter::writeMessage( const char * msg ) const
{
return writeMessage( (void*)(msg), strlen(msg) );
}
/*! This method writes a message to its peer
\param msg message to be written for peer
\param iLength message length
\return int number of charactors sent */
int TDataPorter::writeMessage( const void * msg, int iLength ) const
{
if( !active() || getConnectionType() != CONN_TCP )
return -1;
return ( write( getSocketFD(), msg, iLength ) );
}
/*! This method reads messages from a network connection
\param msg buffer to write message to
\param iLength Maximum length of buffer
\return int number of bytes totally read */
int TDataPorter::readMessage( void * msg, int iLength ) const
{
fd_set fds;
FD_ZERO( &fds );
FD_SET( getSocketFD(), &fds );
((char*)msg)[0] = '\0';
if( select( getSocketFD() + 1, &fds, 0, 0, 0 ) > 0 )
read( getSocketFD(), msg, iLength );
else
return false;
return true;
}
/*! This method determines wheather this socket is active or not
\return bool wheather connection is open */
bool TDataPorter::active() const
{
return ( m_SocketFD != -1 );
}
/*! This method waits for data to arrive on socket, waits until data
comes or a time-out event occures
\param fds Internal variable to synch
\param iSecs seconds to wait until data time-out occures */
int TDataPorter::waitForData( fd_set & fds, int iSecs ) const
{
timeval tv;
tv.tv_sec = iSecs;
tv.tv_usec = 1000000;
FD_ZERO( &fds );
FD_SET( this->getSocketFD(), &fds );
return ( select( getSocketFD() + 1, &fds, NULL, NULL, &tv ) >= 0 );
}
/*! This method opens the socket for the first time & initializes
the socket properties
\return bool indicating update was successful */
bool TDataPorter::open()
{
if( active() )
return false;
int conn = ( m_ConnectionType == CONN_TCP ? SOCK_STREAM : SOCK_DGRAM );
int yes = 1;
if( ( m_SocketFD = socket(PF_INET, conn, 0) ) == -1 )
{
perror( "TDataPorter::socket" );
return false;
}
if( setsockopt( m_SocketFD, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int) ) == -1 )
{
perror( "TDataPorter::setsockopt" );
return false;
}
return true;
}
/*! This method re-initializes the socket connection
\return bool indicating wheather update was successful */
bool TDataPorter::reOpen()
{
closeAll();
open();
return true;
}
/*! This method closes socket connections and clears internal fields
\return bool inidicating wheather socket closed normally or not*/
bool TDataPorter::closeAll()
{
if( !active() )
return false;
close( m_SocketFD );
m_SocketFD = -1;
return true;
}
/********************************************************************/
/*********************** Class TConnection ************************/
/********************************************************************/
/*! This is the constructor for TConnection class which encapsulates
connection routines under linux API, like listen(), accept() and
others; Initializes with connection mode: TCP/UDP
\param conn Connection mode to use: TCP/IP & UDP/IP are supported
\param strHost hostname to connect to
\param iPort Port to connect to on remote host
*/
TConnection::TConnection( ConnectionT conn, const char *strHost, int iPort )
{
m_SelfAddress.sin_family = AF_INET; // host byte order
m_SelfAddress.sin_port = htons( 0 ); // short, network byte order
m_SelfAddress.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
memset( &(m_SelfAddress.sin_zero), '\0', 8 ); // zero the rest of the struct
m_SocketFD = new TDataPorter( conn );
if( *strHost && iPort != -1 )
openConnection( strHost, iPort );
}
/*! This is the destructor of TConnection which closes available
connections and frees up all memory used */
TConnection::~TConnection()
{
closeConnection();
delete m_SocketFD;
};
/*! This method returns wheather connection is made or not
\return bool wheather connection is active */
bool TConnection::connected() const
{
return m_SocketFD->active();
}
/*! This method returns connection mode, ie. TCP/UDP
\return bool indicating connection mode */
ConnectionT TConnection::getConnectionType() const
{
return m_SocketFD->getConnectionType();
}
/*! This method returns local port assigned to connection
\return int current local port being used */
int TConnection::getLocalPort( ) const
{
return m_SelfAddress.sin_port;
}
/*! This method sets local port to use
\param iPort port to use for connections
\return bool wheather update was successful */
bool TConnection::setLocalPort( int iPort )
{
if( connected() )
return false;
m_SelfAddress.sin_port = iPort;
return true;
}
/*! This method returns socket descriptor
\return socket descriptor */
int TConnection::getSocketFD() const
{
return m_SocketFD->getSocketFD();
}
/*! This method makes a network connection to a server
listening for connection
\param str hostname to connect to
\param iPort port to connect on remote machine
\return bool wheather connection is made or not */
bool TConnection::openConnection( const char *str, int iPort )
{
struct hostent *he;
if( ( he = gethostbyname( str ) ) == NULL )
{ // get the host info
herror( "TConnection::gethostbyname" );
return false;
}
m_SocketFD->reOpen();
m_Remote.sin_family = AF_INET; // host byte order
m_Remote.sin_port = htons(iPort); // short, network byte order
m_Remote.sin_addr = *((struct in_addr *)he->h_addr);
memset( &(m_Remote.sin_zero), '\0', 8 ); // zero the rest of the struct
if( getConnectionType() == CONN_TCP &&
connect( m_SocketFD->getSocketFD(), (struct sockaddr *)&m_Remote, sizeof(struct sockaddr)) == -1 )
{
perror("TConnection::openConnection");
return false;
}
return true;
}
/*! This method starts listening on port specified
for any connection to be made
\param iPort port to start listening on
\return bool wheather server started listening or not */
bool TConnection::startServer( int iPort )
{
if( connected() )
return false;
m_SocketFD->reOpen();
m_SelfAddress.sin_port = htons( iPort ); // short, network byte order
if( bind( m_SocketFD->getSocketFD(), (struct sockaddr *)&m_SelfAddress, sizeof(struct sockaddr) ) == -1 )
{
perror("TConnection::bind");
return false;
}
if( getConnectionType() == CONN_TCP && listen( m_SocketFD->getSocketFD(), MAX_CONN_QUEUE ) == -1 )
{
perror("TConnection::listen");
return false;
}
return true;
}
/*! This method waits until a connection is made and a
client asked for a connection
\return bool if listening was successful */
bool TConnection::waitForConnection()
{
if( getConnectionType() != CONN_TCP )
return false;
int new_fd;
sockaddr_in their_addr;
socklen_t sin_size = sizeof(struct sockaddr_in);
if( ( new_fd = accept( m_SocketFD->getSocketFD(), (struct sockaddr *)&their_addr, &sin_size ) ) == -1 )
{
perror("TConnection::accept");
return false;
}
cout << "server: got connection from " << inet_ntoa(their_addr.sin_addr) << END;
if( !fork() )
{ // this is the child process
m_SocketFD->closeAll(); // child doesn’t need the listener
TDataPorter new_socket( CONN_TCP, new_fd );
new_socket.sendMessage( "Hello, world!\n", 14 );
new_socket.closeAll();
exit(0);
}
close(new_fd); // parent doesn’t need this
return true;
}
/*! This method closes connections on client side,
or stops listening with servers
\return bool wheather any connection was closed */
bool TConnection::closeConnection()
{
if(!connected())
return false;
m_SocketFD->closeAll();
return true;
}
/*! This method waits for data to be recieved to the socket
\param time_out time in seconds for socket to determine
packets are availabe
\return bool indicating socket status */
bool TConnection::waitForData( int time_out ) const
{
fd_set fds;
return ( m_SocketFD->waitForData( fds, time_out ) >= 0 );
}
/*! This method sends a message via a network socket connection made
\param strMsg message to send via network connection
\return bool wheather message was sent */
bool TConnection::sendMessage( const char * strMsg ) const
{
return ( sendData( (void*)strMsg, strlen(strMsg) ) );
}
/*! This method sends a message via a network socket connection made
\param data message to send via network connection
\param iLength Length of the message
\return bool wheather message was sent */
bool TConnection::sendData( const void * data, int iLength ) const
{
if( !connected() )
return false;
if( m_SocketFD->getConnectionType() == CONN_TCP )
return ( m_SocketFD->sendMessage( data, iLength ) > 0 ? true : false );
else
return ( m_SocketFD->sendMessageUDP( data, iLength, &m_Remote ) > 0 ? true : false );
}
/*! This method writes a message to its connected peer
\param msg Message to be written for peer
\return bool indicating wheather message was written or not */
bool TConnection::writeMessage( const char * msg ) const
{
return writeMessage( (void*)msg, strlen(msg) );
}
/*! This method writes a message to its connected peer
\param msg Message to be written for peer
\param iLength Message length
\return bool indicating wheather message was written or not */
bool TConnection::writeMessage( const void * msg, int iLength ) const
{
return ( m_SocketFD->writeMessage( msg, iLength ) );
}
/*! This method checks for data to recieve on the connection and
returns recieved data
\param strMsg place for recieved data to be written on
\param iMaxLen maximum length of place to store data on
\param time_out maximum t ime to wait for socket to
\param close_empty Close the connection if no data recieved
\return bool wheather any data was recieved */
bool TConnection::recvMessage( char * strMsg, int iMaxLen, int time_out, bool close_empty )
{
if( !connected() )
return false;
int iBytesRecieved = m_SocketFD->recvMessage( strMsg, iMaxLen - 1, time_out );
if( iBytesRecieved == -1 )
return false;
else if( iBytesRecieved == 0 )
{
if( close_empty )
{
cerr << "Nothing recieved, probably a dead connection, disconnecting" << END;
closeConnection();
}
return false;
}
else
return true;
}
/*! This method reads a message from the connection. When there is
no message available, it does not wait for one.
\param msg string in which message is stored
\param iMaxLength Maximum length of the message
\return bool indicating any message were read or not */
bool TConnection::readMessage( void * msg, int iMaxLength ) const
{
return ( m_SocketFD->readMessage( msg, iMaxLength ) > 0 );
}
/********************************************************************/
/******************* Class TRoboCupConnection *********************/
/********************************************************************/
/*! TRoboCupConnection constructor to create & initialize connection
to simulation server */
TRoboCupConnection::TRoboCupConnection( const char * strHost, int iPort ) : TConnection( CONN_TCP, strHost, iPort )
{
}
/*! TRoboCupConnection destructor, only closes connections and frees
up memory */
TRoboCupConnection::~TRoboCupConnection()
{
closeConnection();
}
/*! This method is the only part needed for sending commands to
simulation server, when a connection is ready
\param msg message to send to the server
\return bool wheather command was sent or not */
bool TRoboCupConnection::sendCommand( const char * msg ) const
{
unsigned int len = htonl( strlen(msg) );
string prefix( (const char*)&len, sizeof(unsigned int) );
string str = prefix + msg;
//CommLogger << "Client -> Serever: \"" << str << "\"" << END;
gLog <<"[send ] "<< string(str) << END << END << END;
gVisionInfoLog << "[send ] " << string(str) << END << END << END;
return ( write( getSocketFD(), str.data(), str.size() ) >= 0 );
}
/*! This method is the only routine needed to get the simulation
server messages
\param msg place to write message recieved to
\param iMaxLen maximum buffer capacity
\return bool indicating wheather any message is recieved */
bool TRoboCupConnection::getMessage( char * msg, int iMaxLen ) const
{
char buffer[16 * 1024];
unsigned int bytesRead = read( m_SocketFD->getSocketFD(), buffer, sizeof(buffer));
if( bytesRead < sizeof(unsigned int) )
{
//gLog << " bytesRead < sizeof(unsigned int) " << bytesRead << endl;
bytesRead = 0;
return false;
}
// msg is prefixed with it's total length
unsigned int msgLen = ntohl(*(unsigned int*)buffer);
if( msgLen > (unsigned)iMaxLen )
{
//gLog << " msgLen > (unsigned)iMaxLen " << msgLen << endl;
//bytesRead = iMaxLen;
return false;
}
// read remaining message segments
unsigned int msgRead = bytesRead - sizeof(unsigned int);
char *offset = buffer + bytesRead;
while( msgRead < msgLen )
{
fd_set fds;
FD_ZERO( &fds );
FD_SET( m_SocketFD->getSocketFD(), &fds );
if( select(m_SocketFD->getSocketFD() + 1, &fds, 0, 0, 0) > 0 )
{
msgRead += read(m_SocketFD->getSocketFD(), offset, sizeof(buffer) - msgRead);
offset += msgRead;
}
}
// zero terminate received data
(*offset) = 0;
strcpy( (char*)msg, string(buffer+sizeof(unsigned int) ).data() );
//CommLogger << "Server -> Client: \"" << msg << "\"" << "\n";
//Log_Logger <<"[recv] "<< msg << END;
//Log_Logger << END << END << END;
gLog <<"[recv ] "<< msg << END;
gVisionInfoLog <<"[recv ] "<< msg << END;
return true;
}