-
Notifications
You must be signed in to change notification settings - Fork 463
/
FGfdmSocket.cpp
453 lines (377 loc) · 12.8 KB
/
FGfdmSocket.cpp
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
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGfdmSocket.cpp
Author: Jon S. Berndt
Date started: 11/08/99
Purpose: Encapsulates a socket
Called by: FGOutput, et. al.
------------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be
found on the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This class excapsulates a socket for simple data writing
HISTORY
--------------------------------------------------------------------------------
11/08/99 JSB Created
11/08/07 HDW Added Generic Socket Send
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <ws2tcpip.h>
#elif defined(__OpenBSD__)
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#else
#include <fcntl.h>
#include <unistd.h>
#endif
#include <iomanip>
#include <iostream>
#include <sstream>
#include <cstring>
#include "FGfdmSocket.h"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
#ifndef _WIN32
// On BSD/Unix, defining the flags INVALID_SOCKET and SOCKET_ERROR to -1 allows
// using the same syntax for Windows and BSD/Unix platforms.
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#endif
namespace JSBSim {
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifdef _WIN32
static bool LoadWinSockDLL(int debug_lvl)
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData)) {
cerr << "Winsock DLL not initialized ..." << endl;
return false;
}
if (debug_lvl > 0)
cout << "Winsock DLL loaded ..." << endl;
return true;
}
#endif
FGfdmSocket::FGfdmSocket(const string& address, int port, int protocol, int precision)
{
sckt = sckt_in = INVALID_SOCKET;
Protocol = (ProtocolType)protocol;
connected = false;
struct addrinfo *addr = nullptr;
this->precision = precision;
#ifdef _WIN32
if (!LoadWinSockDLL(debug_lvl)) return;
#endif
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
if (protocol == ptUDP)
hints.ai_socktype = SOCK_DGRAM;
else
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
if (!is_number(address))
hints.ai_flags = AI_ADDRCONFIG;
else
hints.ai_flags = AI_NUMERICHOST;
int failure = getaddrinfo(address.c_str(), NULL, &hints, &addr);
if (failure || !addr) {
cerr << "Could not get host net address " << address;
if (hints.ai_flags == AI_NUMERICHOST)
cerr << " by number..." << endl;
else
cerr << " by name..." << endl;
cerr << gai_strerror(failure) << endl;
freeaddrinfo(addr);
return;
}
sckt = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (debug_lvl > 0) {
if (protocol == ptUDP) //use udp protocol
cout << "Creating UDP socket on port " << port << endl;
else //use tcp protocol
cout << "Creating TCP socket on port " << port << endl;
}
if (sckt != INVALID_SOCKET) { // successful
int len = sizeof(struct sockaddr_in);
memcpy(&scktName, addr->ai_addr, len);
scktName.sin_port = htons(port);
if (connect(sckt, (struct sockaddr*)&scktName, len) == 0) { // successful
if (debug_lvl > 0)
cout << "Successfully connected to socket for output ..." << endl;
connected = true;
} else // unsuccessful
cerr << "Could not connect to socket for output ..." << endl;
} else // unsuccessful
cerr << "Could not create socket for FDM output, error = " << errno << endl;
freeaddrinfo(addr);
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// assumes TCP or UDP socket on localhost, for inbound datagrams
FGfdmSocket::FGfdmSocket(int port, int protocol, int precision)
{
sckt = INVALID_SOCKET;
connected = false;
Protocol = (ProtocolType)protocol;
string ProtocolName;
this->precision = precision;
#ifdef _WIN32
if (!LoadWinSockDLL(debug_lvl)) return;
#endif
if (Protocol == ptUDP) { //use udp protocol
ProtocolName = "UDP";
sckt = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
#ifdef _WIN32
u_long NonBlock = 1; // True
ioctlsocket(sckt, FIONBIO, &NonBlock);
#else
int flags = fcntl(sckt, F_GETFL, 0);
fcntl(sckt, F_SETFL, flags | O_NONBLOCK);
#endif
}
else {
ProtocolName = "TCP";
sckt = socket(AF_INET, SOCK_STREAM, 0);
}
if (debug_lvl > 0)
cout << "Creating input " << ProtocolName << " socket on port " << port
<< endl;
if (sckt != INVALID_SOCKET) {
memset(&scktName, 0, sizeof(struct sockaddr_in));
scktName.sin_family = AF_INET;
scktName.sin_port = htons(port);
if (Protocol == ptUDP)
scktName.sin_addr.s_addr = htonl(INADDR_ANY);
socklen_t len = sizeof(struct sockaddr_in);
if (bind(sckt, (struct sockaddr*)&scktName, len) != SOCKET_ERROR) {
if (debug_lvl > 0)
cout << "Successfully bound to " << ProtocolName
<< " input socket on port " << port << endl << endl;
if (Protocol == ptTCP) {
if (listen(sckt, 5) != SOCKET_ERROR) { // successful listen()
#ifdef _WIN32
u_long NoBlock = 1;
ioctlsocket(sckt, FIONBIO, &NoBlock);
#else
int flags = fcntl(sckt, F_GETFL, 0);
fcntl(sckt, F_SETFL, flags | O_NONBLOCK);
#endif
sckt_in = accept(sckt, (struct sockaddr*)&scktName, &len);
connected = true;
} else
cerr << "Could not listen ..." << endl;
} else
connected = true;
} else // unsuccessful
cerr << "Could not bind to " << ProtocolName << " input socket, error = "
<< errno << endl;
} else // unsuccessful
cerr << "Could not create " << ProtocolName << " socket for input, error = "
<< errno << endl;
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGfdmSocket::~FGfdmSocket()
{
if (sckt != INVALID_SOCKET) shutdown(sckt,2);
if (sckt_in != INVALID_SOCKET) shutdown(sckt_in,2);
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGfdmSocket::Receive(void)
{
char buf[1024];
socklen_t len = sizeof(struct sockaddr_in);
string data; // todo: should allocate this with a standard size as a
// class attribute and pass as a reference?
if (sckt_in == INVALID_SOCKET && Protocol == ptTCP) {
sckt_in = accept(sckt, (struct sockaddr*)&scktName, &len);
if (sckt_in != INVALID_SOCKET) {
#ifdef _WIN32
u_long NoBlock = 1;
ioctlsocket(sckt_in, FIONBIO, &NoBlock);
#else
int flags = fcntl(sckt_in, F_GETFL, 0);
fcntl(sckt_in, F_SETFL, flags | O_NONBLOCK);
#endif
send(sckt_in, "Connected to JSBSim server\n\rJSBSim> ", 36, 0);
}
}
if (sckt_in != INVALID_SOCKET) {
int num_chars;
while ((num_chars = recv(sckt_in, buf, sizeof buf, 0)) > 0) {
data.append(buf, num_chars);
}
#ifdef _WIN32
// when nothing received and the error isn't "would block"
// then assume that the client has closed the socket.
if (num_chars == 0) {
DWORD err = WSAGetLastError();
if (err != WSAEWOULDBLOCK) {
cout << "Socket Closed. Back to listening" << endl;
closesocket(sckt_in);
sckt_in = INVALID_SOCKET;
}
}
#endif
}
// this is for FGUDPInputSocket
if (sckt != INVALID_SOCKET && Protocol == ptUDP) {
struct sockaddr addr;
socklen_t fromlen = sizeof addr;
int num_chars = recvfrom(sckt, buf, sizeof buf, 0, (struct sockaddr*)&addr, &fromlen);
if (num_chars > 0) data.append(buf, num_chars);
}
return data;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
int FGfdmSocket::Reply(const string& text)
{
int num_chars_sent=0;
if (sckt_in != INVALID_SOCKET) {
num_chars_sent = send(sckt_in, text.c_str(), text.size(), 0);
send(sckt_in, "JSBSim> ", 8, 0);
} else {
cerr << "Socket reply must be to a valid socket" << endl;
return -1;
}
return num_chars_sent;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::Close(void)
{
#ifdef _WIN32
closesocket(sckt_in);
#else
close(sckt_in);
#endif
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::Clear(void)
{
buffer.str(string());
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::Clear(const string& s)
{
Clear();
buffer << s << ' ';
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::Append(const char* item)
{
if (buffer.tellp() > 0) buffer << ',';
buffer << item;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::Append(double item)
{
if (buffer.tellp() > 0) buffer << ',';
buffer << std::setw(12) << std::setprecision(precision) << item;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::Append(long item)
{
if (buffer.tellp() > 0) buffer << ',';
buffer << std::setw(12) << item;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::Send(void)
{
buffer << '\n';
string str = buffer.str();
if ((send(sckt,str.c_str(),str.size(),0)) <= 0) {
perror("send");
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::Send(const char *data, int length)
{
if ((send(sckt,data,length,0)) <= 0) {
perror("send");
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGfdmSocket::WaitUntilReadable(void)
{
if (sckt_in == INVALID_SOCKET)
return;
fd_set fds;
FD_ZERO(&fds);
FD_SET(sckt_in, &fds);
#ifdef _WIN32
select(0, &fds, nullptr, nullptr, nullptr);
#else
select(sckt_in+1, &fds, nullptr, nullptr, nullptr);
#endif
/*
If you want to check select return status:
int recVal = select(sckt_in+1, &fds, nullptr, nullptr, nullptr);
recVal: received value
0, if socket timeout
-1, if socket error
anithing else, if socket is readable
*/
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGfdmSocket::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGfdmSocket" << endl;
if (from == 1) cout << "Destroyed: FGfdmSocket" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
}
}
}
}