1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 Module: FGfdmSocket.cpp
6 Purpose: Encapsulates a socket
7 Called by: FGOutput, et. al.
9 ------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) -------------
11 This program is free software; you can redistribute it and/or modify it under
12 the terms of the GNU Lesser General Public License as published by the Free Software
13 Foundation; either version 2 of the License, or (at your option) any later
16 This program is distributed in the hope that it will be useful, but WITHOUT
17 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21 You should have received a copy of the GNU Lesser General Public License along with
22 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
23 Place - Suite 330, Boston, MA 02111-1307, USA.
25 Further information about the GNU Lesser General Public License can also be found on
26 the world wide web at http://www.gnu.org.
28 FUNCTIONAL DESCRIPTION
29 --------------------------------------------------------------------------------
30 This class excapsulates a socket for simple data writing
33 --------------------------------------------------------------------------------
35 11/08/07 HDW Added Generic Socket Send
37 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
41 #include "FGfdmSocket.h"
45 static const char *IdSrc = "$Id$";
46 static const char *IdHdr = ID_FDMSOCKET;
48 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
50 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
52 FGfdmSocket::FGfdmSocket(string address, int port, int protocol)
54 sckt = sckt_in = size = 0;
57 #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
60 wsaReturnCode = WSAStartup(MAKEWORD(1,1), &wsaData);
61 if (wsaReturnCode == 0) cout << "Winsock DLL loaded ..." << endl;
62 else cout << "Winsock DLL not initialized ..." << endl;
65 if (address.find_first_not_of("0123456789.",0) != address.npos) {
66 if ((host = gethostbyname(address.c_str())) == NULL) {
67 cout << "Could not get host net address by name..." << endl;
70 if ((host = gethostbyaddr(address.c_str(), address.size(), PF_INET)) == NULL) {
71 cout << "Could not get host net address by number..." << endl;
76 if (protocol == ptUDP) { //use udp protocol
77 sckt = socket(AF_INET, SOCK_DGRAM, 0);
78 cout << "Creating UDP socket on port " << port << endl;
80 else { //use tcp protocol
81 sckt = socket(AF_INET, SOCK_STREAM, 0);
82 cout << "Creating TCP socket on port " << port << endl;
85 if (sckt >= 0) { // successful
86 memset(&scktName, 0, sizeof(struct sockaddr_in));
87 scktName.sin_family = AF_INET;
88 scktName.sin_port = htons(port);
89 memcpy(&scktName.sin_addr, host->h_addr_list[0], host->h_length);
90 int len = sizeof(struct sockaddr_in);
91 if (connect(sckt, (struct sockaddr*)&scktName, len) == 0) { // successful
92 cout << "Successfully connected to socket for output ..." << endl;
94 } else { // unsuccessful
95 cout << "Could not connect to socket for output ..." << endl;
97 } else { // unsuccessful
98 cout << "Could not create socket for FDM output, error = " << errno << endl;
104 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
106 FGfdmSocket::FGfdmSocket(string address, int port)
108 sckt = sckt_in = size = 0;
111 #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
114 wsaReturnCode = WSAStartup(MAKEWORD(1,1), &wsaData);
115 if (wsaReturnCode == 0) cout << "Winsock DLL loaded ..." << endl;
116 else cout << "Winsock DLL not initialized ..." << endl;
119 cout << "... Socket Configuration Sanity Check ..." << endl;
120 cout << "Host name... " << address << ", Port... " << port << "." << endl;
121 cout << "Host name... (char) " << address.c_str() << "." << endl;
123 if (address.find_first_not_of("0123456789.",0) != address.npos) {
124 if ((host = gethostbyname(address.c_str())) == NULL) {
125 cout << "Could not get host net address by name..." << endl;
128 if ((host = gethostbyaddr(address.c_str(), address.size(), PF_INET)) == NULL) {
129 cout << "Could not get host net address by number..." << endl;
134 cout << "Got host net address..." << endl;
135 sckt = socket(AF_INET, SOCK_STREAM, 0);
137 if (sckt >= 0) { // successful
138 memset(&scktName, 0, sizeof(struct sockaddr_in));
139 scktName.sin_family = AF_INET;
140 scktName.sin_port = htons(port);
141 memcpy(&scktName.sin_addr, host->h_addr_list[0], host->h_length);
142 int len = sizeof(struct sockaddr_in);
143 if (connect(sckt, (struct sockaddr*)&scktName, len) == 0) { // successful
144 cout << "Successfully connected to socket for output ..." << endl;
146 } else { // unsuccessful
147 cout << "Could not connect to socket for output ..." << endl;
149 } else { // unsuccessful
150 cout << "Could not create socket for FDM output, error = " << errno << endl;
156 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
158 FGfdmSocket::FGfdmSocket(int port)
162 unsigned long NoBlock = true;
164 #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
167 wsaReturnCode = WSAStartup(MAKEWORD(1,1), &wsaData);
168 if (wsaReturnCode == 0) cout << "Winsock DLL loaded ..." << endl;
169 else cerr << "Winsock DLL not initialized ..." << endl;
172 sckt = socket(AF_INET, SOCK_STREAM, 0);
174 if (sckt >= 0) { // successful
175 memset(&scktName, 0, sizeof(struct sockaddr_in));
176 scktName.sin_family = AF_INET;
177 scktName.sin_port = htons(port);
178 int len = sizeof(struct sockaddr_in);
179 if (bind(sckt, (struct sockaddr*)&scktName, len) == 0) { // successful
180 cout << "Successfully bound to socket for input on port " << port << endl;
181 if (listen(sckt, 5) >= 0) { // successful listen()
182 #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
183 ioctlsocket(sckt, FIONBIO, &NoBlock);
184 sckt_in = accept(sckt, (struct sockaddr*)&scktName, &len);
186 ioctl(sckt, FIONBIO, &NoBlock);
187 sckt_in = accept(sckt, (struct sockaddr*)&scktName, (socklen_t*)&len);
190 cerr << "Could not listen ..." << endl;
193 } else { // unsuccessful
194 cerr << "Could not bind to socket for input ..." << endl;
196 } else { // unsuccessful
197 cerr << "Could not create socket for FDM input, error = " << errno << endl;
203 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
205 FGfdmSocket::~FGfdmSocket()
208 if (sckt) shutdown(sckt,2);
209 if (sckt_in) shutdown(sckt_in,2);
218 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
220 string FGfdmSocket::Receive(void)
223 int len = sizeof(struct sockaddr_in);
226 unsigned long NoBlock = true;
227 string data = ""; // todo: should allocate this with a standard size as a
228 // class attribute and pass as a reference?
231 #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
232 sckt_in = accept(sckt, (struct sockaddr*)&scktName, &len);
234 sckt_in = accept(sckt, (struct sockaddr*)&scktName, (socklen_t*)&len);
237 #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
238 ioctlsocket(sckt_in, FIONBIO,&NoBlock);
240 ioctl(sckt_in, FIONBIO, &NoBlock);
242 send(sckt_in, "Connected to JSBSim server\nJSBSim> ", 35, 0);
247 while ((num_chars = recv(sckt_in, buf, 1024, 0)) > 0) {
248 data += string(buf).substr(0,num_chars);
249 total_chars += num_chars;
252 #if defined(_MSC_VER)
253 // when nothing received and the error isn't "would block"
254 // then assume that the client has closed the socket.
255 if (num_chars == 0) {
256 DWORD err = WSAGetLastError ();
257 if (err != WSAEWOULDBLOCK) {
258 printf ("Socket Closed. back to listening\n");
259 closesocket (sckt_in);
266 return data.substr(0, total_chars);
269 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
271 int FGfdmSocket::Reply(string text)
273 int num_chars_sent=0;
276 num_chars_sent = send(sckt_in, text.c_str(), text.size(), 0);
277 send(sckt_in, "JSBSim> ", 8, 0);
279 cerr << "Socket reply must be to a valid socket" << endl;
282 return num_chars_sent;
285 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
287 void FGfdmSocket::Close(void)
292 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
294 void FGfdmSocket::Clear(void)
300 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
302 void FGfdmSocket::Clear(string s)
305 size = buffer.size();
308 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
310 void FGfdmSocket::Append(const char* item)
312 if (size == 0) buffer += string(item);
313 else buffer += string(",") + string(item);
317 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
319 void FGfdmSocket::Append(double item)
323 sprintf(s,"%12.7f",item);
325 if (size == 0) buffer += string(s);
326 else buffer += string(",") + string(s);
330 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
332 void FGfdmSocket::Append(long item)
336 sprintf(s,"%12ld",item);
338 if (size == 0) buffer += string(s);
339 else buffer += string(",") + string(s);
343 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
345 void FGfdmSocket::Send(void)
347 buffer += string("\n");
348 if ((send(sckt,buffer.c_str(),buffer.size(),0)) <= 0) {
354 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
356 void FGfdmSocket::Send(char *data, int length)
358 if ((send(sckt,data,length,0)) <= 0) {
364 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
365 // The bitmasked value choices are as follows:
366 // unset: In this case (the default) JSBSim would only print
367 // out the normally expected messages, essentially echoing
368 // the config files as they are read. If the environment
369 // variable is not set, debug_lvl is set to 1 internally
370 // 0: This requests JSBSim not to output any messages
372 // 1: This value explicity requests the normal JSBSim
374 // 2: This value asks for a message to be printed out when
375 // a class is instantiated
376 // 4: When this value is set, a message is displayed when a
377 // FGModel object executes its Run() method
378 // 8: When this value is set, various runtime state variables
379 // are printed out periodically
380 // 16: When set various parameters are sanity checked and
381 // a message is printed out when they go out of bounds
383 void FGfdmSocket::Debug(int from)
385 if (debug_lvl <= 0) return;
387 if (debug_lvl & 1) { // Standard console startup message output
388 if (from == 0) { // Constructor
391 if (debug_lvl & 2 ) { // Instantiation/Destruction notification
392 if (from == 0) cout << "Instantiated: FGfdmSocket" << endl;
393 if (from == 1) cout << "Destroyed: FGfdmSocket" << endl;
395 if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
397 if (debug_lvl & 8 ) { // Runtime state variables
399 if (debug_lvl & 16) { // Sanity checking
401 if (debug_lvl & 64) {
402 if (from == 0) { // Constructor
403 cout << IdSrc << endl;
404 cout << IdHdr << endl;