dd5d377086309c62c9df77b1cb48200fc8a78608
[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         if (connect(m_iSock, (struct sockaddr *) &m_addrRemote, sizeof(struct sockaddr)) == -1) {
53
54                 perror("IoTSocketClient: Connect m_iSock error!");
55                 return;
56         }
57
58         // Send out request for reversed bits or not
59         char temp[1];
60         if (bReverse) {
61
62                 temp[0] = 1;
63                 if (send(m_iSock, temp, 1, 0) == -1)
64                 {
65                         perror("IoTSocketClient: Send 1 error!");
66                         return;
67                 }
68         } else {
69                 temp[0] = 0;
70                 if (send(m_iSock, temp, 1, 0) == -1)
71                 {
72                         perror("IoTSocketClient: Send 2 error!");
73                         return;
74                 }
75         }
76         
77         if (pResult)
78                 *pResult = true;
79 }
80
81
82 #endif