1 /** Class IoTSocket is a base class for IoTSocketServer.cpp
2 * and IoTSocketClient.cpp that provide interfaces to connect
3 * to either Java or C++ socket endpoint
5 * Adapted from Java/C++ socket implementation
7 * @see <a href="https://www.keithv.com/software/socket/</a>
9 * @author Rahmadi Trimananda <rtrimana @ uci.edu>
13 #ifndef _IOTSOCKET_HPP__
14 #define _IOTSOCKET_HPP__
16 // Adds in the send/recv acks after each message.
19 static const int SOCKET_BUFF_SIZE = 64000;
25 #include <sys/types.h>
27 #include <netinet/in.h>
29 #include <sys/socket.h>
33 // Duplicated from winsock2.h
34 #define SD_RECEIVE 0x00
41 IoTSocket(int iPort, bool* pResult);
44 bool close(); // Close the socket
45 bool sendBytes(char* pVals, int _iLen); // Send a set of bytes
46 char* receiveBytes(char* pVals, int* len); // Receive a set of bytes
49 int m_iPort; // Port I'm listening on
50 int m_iSock; // Socket connection
51 struct sockaddr_in m_addrRemote; // Connector's address information
52 double* m_pBuffer; // Reuse the same memory for buffer
61 IoTSocket::IoTSocket(int iPort, bool* pResult) {
67 // Allocate our temporary buffers that are used to convert data types
68 m_pBuffer = (double *) malloc(sizeof(double) * SOCKET_BUFF_SIZE);
70 perror("IoTSocket: Failed to malloc buffer!");
78 IoTSocket::~IoTSocket() {
87 // Send bytes over the wire
88 bool IoTSocket::sendBytes(char* pVals, int _iLen) {
95 if (send(m_iSock, size, 1, 0) == -1) {
96 perror("IoTSocket: Send size error!");
100 if (send(m_iSock, (char *) pVals, iLen, 0) == -1) {
101 perror("IoTSocket: Send bytes error!");
115 // Receive bytes, returns number of bytes received
116 // Generate an array of char on the heap and return it
117 char* IoTSocket::receiveBytes(char* pVals, int* len)
129 while ((iTotal < 1) && (iResult != -1)) {
130 iResult = recv(m_iSock, size, 1, 0);
134 perror("IoTSocket: Receive size error!");
137 int iLen = (int) size[0];
138 // To be returned from this method...
140 pVals = new char[iLen];
141 pTemp = (char *) m_pBuffer;
142 // We receiving the incoming ints one byte at a time.
144 if ((iNumBytes = recv(m_iSock, pTemp, SOCKET_BUFF_SIZE, 0)) == -1) {
145 perror("IoTSocket: Receive error!");
148 for (i = 0; i < iNumBytes; i++) {
152 iTotalBytes += iNumBytes;
153 if (iTotalBytes == iLen)
166 // Shut down the socket
167 bool IoTSocket::close()
169 if (shutdown(m_iSock, SD_BOTH) == -1) {
170 perror("IoTSocket: Close error!");
178 // Receive a short ack from the client
179 bool IoTSocket::receiveAck()
184 while ((iTotal < 1) && (iResult != -1)) {
186 iResult = recv(m_iSock, temp, 1, 0);
191 perror("IoTSocket: ReceiveAck error!");
199 // Send a short ack to the client
200 bool IoTSocket::sendAck()
205 if (send(m_iSock, temp, 1, 0) == -1)