2 // g++ -O2 -g -pedantic -Wall fgfsclient.cxx -o fgfsclient -lstdc++
8 #include <netinet/in.h>
12 #include <sys/socket.h>
14 #include <sys/types.h>
18 const int maxlen = 256;
26 FGFSSocket(const char *name, const unsigned port);
27 ~FGFSSocket() { close(); };
29 int write(const char *msg, ...);
30 const char *read(void);
31 inline void flush(void);
32 void settimeout(unsigned t) { timeout = t; };
38 FGFSSocket::FGFSSocket(const char *hostname = "localhost", const unsigned port = 5501)
44 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
46 throw("FGFSSocket/socket");
48 struct hostent *hostinfo;
49 hostinfo = gethostbyname(hostname);
52 throw("FGFSSocket/gethostbyname: unknown host");
55 struct sockaddr_in serv_addr;
56 serv_addr.sin_family = AF_INET;
57 serv_addr.sin_port = htons(port);
58 serv_addr.sin_addr = *(struct in_addr *)hostinfo->h_addr;
60 if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
62 throw("FGFSSocket/connect");
74 int FGFSSocket::close(void)
80 int ret = ::close(sock);
86 int FGFSSocket::write(const char *msg, ...)
98 if (!select(FD_SETSIZE, 0, &fd, 0, &tv))
99 throw("FGFSSocket::write/select: timeout exceeded");
102 vsprintf(buf, msg, va);
104 std::cout << "SEND: " << buf << std::endl;
105 strcat(buf, "\015\012");
107 len = ::write(sock, buf, strlen(buf));
109 throw("FGFSSocket::write");
114 const char *FGFSSocket::read(void)
116 static char buf[maxlen];
126 if (!select(FD_SETSIZE, &fd, 0, 0, &tv)) {
130 throw("FGFSSocket::read/select: timeout exceeded");
133 len = ::read(sock, buf, maxlen - 1);
135 throw("FGFSSocket::read/read");
139 for (p = &buf[len - 1]; p >= buf; p--)
140 if (*p != '\015' && *p != '\012')
143 return strlen(buf) ? buf : 0;
147 inline void FGFSSocket::flush(void)
157 int main(const int argc, const char *argv[])
159 const char *hostname = argc > 1 ? argv[1] : "localhost";
160 int port = argc > 2 ? atoi(argv[2]) : 5501;
162 FGFSSocket f(hostname, port);
164 f.write("set /controls/engines/engine[%d]/throttle %lg", 0, 1.0);
165 f.write("set /controls/engines/engine[%d]/throttle %lg", 1, 1.0);
166 f.write("get /sim/aircraft");
167 const char *p = f.read();
169 std::cout << "RECV: " << p << std::endl;
172 } catch (const char s[]) {
173 std::cerr << "Error: " << s << ": " << strerror(errno) << std::endl;
177 std::cerr << "Error: unknown exception" << std::endl;