Adding config file for sharing.
[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 final : 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         if (pResult)
32                 *pResult = false;
33         if ((he = gethostbyname(pStrHost)) == NULL) {
34                 perror("IoTSocketClient: Gethostbyname error!");
35                 return;
36         }
37         if ((m_iSock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
38
39                 perror("IoTSocketClient: Socket error!");
40                 return;
41         }
42
43         m_addrRemote.sin_family         = AF_INET;        
44         m_addrRemote.sin_port           = htons(m_iPort);      
45         m_addrRemote.sin_addr           = *((struct in_addr *) he->h_addr); 
46         memset(&(m_addrRemote.sin_zero), 0, 8);
47
48         // Make socket client wait for socket server to be ready
49         if (connect(m_iSock, (struct sockaddr *) &m_addrRemote, sizeof(struct sockaddr)) == -1) { 
50                 perror("IoTSocketServer: Accept connection error!");
51                 return;
52         }
53
54         // Send out request for reversed bits or not
55         char temp[1];
56         if (bReverse) {
57
58                 temp[0] = 1;
59                 if (send(m_iSock, temp, 1, 0) == -1)
60                 {
61                         perror("IoTSocketClient: Send 1 error!");
62                         return;
63                 }
64         } else {
65                 temp[0] = 0;
66                 if (send(m_iSock, temp, 1, 0) == -1)
67                 {
68                         perror("IoTSocketClient: Send 2 error!");
69                         return;
70                 }
71         }
72         
73         if (pResult)
74                 *pResult = true;
75 }
76
77
78 #endif