2 // g++ -O2 -g -pedantic -Wall fgfsclient.cxx -o fgfsclient -lstdc++
3 // USAGE: ./fgfsclient [hostname [port]]
9 #include <netinet/in.h>
13 #include <sys/socket.h>
15 #include <sys/types.h>
20 const char *HOST = "localhost";
21 const unsigned PORT = 5501;
22 const int BUFLEN = 256;
27 FGFSSocket(const char *name, unsigned port);
30 int write(const char *msg, ...);
31 const char *read(void);
32 inline void flush(void);
33 void settimeout(unsigned t) { _timeout = t; }
45 FGFSSocket::FGFSSocket(const char *hostname = HOST, unsigned port = PORT) :
50 _sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
52 throw("FGFSSocket/socket");
54 struct hostent *hostinfo;
55 hostinfo = gethostbyname(hostname);
58 throw("FGFSSocket/gethostbyname: unknown host");
61 struct sockaddr_in serv_addr;
62 serv_addr.sin_family = AF_INET;
63 serv_addr.sin_port = htons(port);
64 serv_addr.sin_addr = *(struct in_addr *)hostinfo->h_addr;
66 if (connect(_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
68 throw("FGFSSocket/connect");
80 FGFSSocket::~FGFSSocket()
86 int FGFSSocket::close(void)
92 int ret = ::close(_sock);
98 int FGFSSocket::write(const char *msg, ...)
108 tv.tv_sec = _timeout;
110 if (!select(FD_SETSIZE, 0, &fd, 0, &tv))
111 throw("FGFSSocket::write/select: timeout exceeded");
114 vsnprintf(buf, BUFLEN - 2, msg, va);
116 std::cout << "SEND: " << buf << std::endl;
117 strcat(buf, "\015\012");
119 len = ::write(_sock, buf, strlen(buf));
121 throw("FGFSSocket::write");
126 const char *FGFSSocket::read(void)
135 tv.tv_sec = _timeout;
137 if (!select(FD_SETSIZE, &fd, 0, 0, &tv)) {
141 throw("FGFSSocket::read/select: timeout exceeded");
144 len = ::read(_sock, _buffer, BUFLEN - 1);
146 throw("FGFSSocket::read/read");
150 for (p = &_buffer[len - 1]; p >= _buffer; p--)
151 if (*p != '\015' && *p != '\012')
154 return strlen(_buffer) ? _buffer : 0;
158 inline void FGFSSocket::flush(void)
168 int main(const int argc, const char *argv[])
170 const char *hostname = argc > 1 ? argv[1] : "localhost";
171 int port = argc > 2 ? atoi(argv[2]) : 5501;
173 FGFSSocket f(hostname, port);
175 f.write("set /controls/engines/engine[%d]/throttle %lg", 0, 1.0);
176 f.write("set /controls/engines/engine[%d]/throttle %lg", 1, 1.0);
177 f.write("get /sim/aircraft");
178 const char *p = f.read();
180 std::cout << "RECV: " << p << std::endl;
183 } catch (const char s[]) {
184 std::cerr << "Error: " << s << ": " << strerror(errno) << std::endl;
188 std::cerr << "Error: unknown exception" << std::endl;