2 // g++ -O2 -g -pedantic -Wall fgfsclient.cxx -o fgfsclient -lstdc++
7 #include <netinet/in.h>
11 #include <sys/socket.h>
13 #include <sys/types.h>
17 const int maxlen = 256;
25 FGFSSocket(const char *name, const unsigned port);
26 ~FGFSSocket() { close(); };
28 int write(const char *msg, ...);
29 const char *read(void);
30 inline void flush(void);
31 void settimeout(unsigned t) { timeout = t; };
37 FGFSSocket::FGFSSocket(const char *hostname = "localhost", const unsigned port = 5501)
43 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
45 throw("FGFSSocket/socket");
47 struct hostent *hostinfo;
48 hostinfo = gethostbyname(hostname);
51 throw("FGFSSocket/gethostbyname: unknown host");
54 struct sockaddr_in serv_addr;
55 serv_addr.sin_family = AF_INET;
56 serv_addr.sin_port = htons(port);
57 serv_addr.sin_addr = *(struct in_addr *)hostinfo->h_addr;
59 if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
61 throw("FGFSSocket/connect");
73 int FGFSSocket::close(void)
79 int ret = ::close(sock);
85 int FGFSSocket::write(const char *msg, ...)
97 if (!select(FD_SETSIZE, 0, &fd, 0, &tv))
98 throw("FGFSSocket::write/select: timeout exceeded");
101 vsprintf(buf, msg, va);
103 std::cout << "SEND: " << buf << std::endl;
104 strcat(buf, "\015\012");
106 len = ::write(sock, buf, strlen(buf));
108 throw("FGFSSocket::write");
113 const char *FGFSSocket::read(void)
115 static char buf[maxlen];
125 if (!select(FD_SETSIZE, &fd, 0, 0, &tv)) {
129 throw("FGFSSocket::read/select: timeout exceeded");
132 len = ::read(sock, buf, maxlen - 1);
134 throw("FGFSSocket::read/read");
138 for (p = &buf[len - 1]; p >= buf; p--)
139 if (*p != '\015' && *p != '\012')
142 return strlen(buf) ? buf : 0;
146 inline void FGFSSocket::flush(void)
156 int main(const int argc, const char *argv[])
158 const char *hostname = argc > 1 ? argv[1] : "localhost";
159 int port = argc > 2 ? atoi(argv[2]) : 5501;
161 FGFSSocket f(hostname, port);
163 f.write("set /controls/engines/engine[%d]/throttle %lg", 0, 1.0);
164 f.write("set /controls/engines/engine[%d]/throttle %lg", 1, 1.0);
165 f.write("get /sim/aircraft");
166 const char *p = f.read();
168 std::cout << "RECV: " << p << std::endl;
171 } catch (const char s[]) {
172 std::cerr << "Error: " << s << ": " << strerror(errno) << std::endl;
176 std::cerr << "Error: unknown exception" << std::endl;