Fixed compiler for Java code generation (not heavily tested yet, but fixes include...
[iot2.git] / iotjava / iotrmi / C++ / IoTSocketClient.hpp
1 /** Class IoTSocketClient is a communication class
2  *  that provides interfaces to connect to either
3  *  Java or C++ socket endpoint. It inherits the
4  *  methods from IoTSocket.
5  *  <p>
6  *  Adapted from Java/C++ socket implementation
7  *  by Keith Vertanen
8  *  @see        <a href="https://www.keithv.com/software/socket/</a>
9  *
10  * @author      Rahmadi Trimananda <rtrimana @ uci.edu>
11  * @version     1.0
12  * @since       2016-08-17
13  */
14 #ifndef _IOTSOCKETCLIENT_HPP__
15 #define _IOTSOCKETCLIENT_HPP__
16
17 #include "IoTSocket.hpp"
18
19 class IoTSocketClient : public IoTSocket
20 {
21         public:
22                 IoTSocketClient(int iPort, const char* pStrHost, bool bReverse, bool* pResult);
23 };
24
25
26 // Constructor
27 IoTSocketClient::IoTSocketClient(int iPort, const char* pStrHost, bool bReverse, bool* pResult) :
28         IoTSocket(iPort, pResult) {
29
30         struct hostent* he = NULL;
31
32         if (pResult)
33                 *pResult = false;
34
35         if ((he = gethostbyname(pStrHost)) == NULL) {
36
37                 perror("IoTSocketClient: Gethostbyname error!");
38                 return;
39         }
40
41         if ((m_iSock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
42
43                 perror("IoTSocketClient: Socket error!");
44                 return;
45         }
46
47         m_addrRemote.sin_family         = AF_INET;        
48         m_addrRemote.sin_port           = htons(m_iPort);      
49         m_addrRemote.sin_addr           = *((struct in_addr *) he->h_addr); 
50         memset(&(m_addrRemote.sin_zero), 0, 8);
51
52         // Make socket client wait for socket server to be ready
53         while (connect(m_iSock, (struct sockaddr *) &m_addrRemote, sizeof(struct sockaddr)) == -1) { }
54
55         // Send out request for reversed bits or not
56         char temp[1];
57         if (bReverse) {
58
59                 temp[0] = 1;
60                 if (send(m_iSock, temp, 1, 0) == -1)
61                 {
62                         perror("IoTSocketClient: Send 1 error!");
63                         return;
64                 }
65         } else {
66                 temp[0] = 0;
67                 if (send(m_iSock, temp, 1, 0) == -1)
68                 {
69                         perror("IoTSocketClient: Send 2 error!");
70                         return;
71                 }
72         }
73         
74         if (pResult)
75                 *pResult = true;
76 }
77
78
79 #endif