1 /** Class IoTSocketServer 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.
6 * Adapted from Java/C++ socket implementation
8 * @see <a href="https://www.keithv.com/software/socket/</a>
10 * @author Rahmadi Trimananda <rtrimana @ uci.edu>
14 #ifndef _IOTSOCKETSERVER_HPP__
15 #define _IOTSOCKETSERVER_HPP__
17 #include "IoTSocket.hpp"
19 #define BACKLOG 10 // How many pending connections queue will hold
21 class IoTSocketServer final : public IoTSocket
24 IoTSocketServer(int iPort, bool* pResult);
26 bool connect(); // Accept a new connection
29 bool m_bReverse; // Am I reversing byte order or not?
30 int m_iListen; // Descriptor we are listening on
31 struct sockaddr_in m_addrMe; // My address information
36 IoTSocketServer::IoTSocketServer(int iPort, bool* pResult) :
37 IoTSocket(iPort, pResult) {
44 if ((m_iListen = socket(AF_INET, SOCK_STREAM, 0)) == -1)
46 perror("IoTSocketServer: Socket error!");
50 m_addrMe.sin_family = AF_INET; // Host byte order
51 m_addrMe.sin_port = htons(m_iPort); // Short, network byte order
52 m_addrMe.sin_addr.s_addr = INADDR_ANY; // Auto-fill with my IP
53 memset(&(m_addrMe.sin_zero), 0, 8); // Zero the rest of the struct
55 if (bind(m_iListen, (struct sockaddr *) &m_addrMe, sizeof(struct sockaddr)) == -1)
57 // Note, this can fail if the server has just been shutdown and not enough time has elapsed.
58 // See: http://www.developerweb.net/forum/showthread.php?t=2977
59 perror("IoTSocketServer: Bind error!");
63 if (listen(m_iListen, BACKLOG) == -1)
65 perror("IoTSocketServer: Listen error!");
74 // Wait for somebody to connect to us on our port.
75 bool IoTSocketServer::connect()
77 socklen_t iSinSize = (socklen_t) sizeof(struct sockaddr_in);
79 if ((m_iSock = accept(m_iListen, (struct sockaddr *) &m_addrRemote, &iSinSize)) == -1)
81 perror("IoTSocketServer: Accept connection error!");
84 // The client sends us an int to indicate if we should
85 // be reversing byte order on this connection. The client
86 // is sending 0 or 1, so a reversed 0 still looks
87 // like a 0, no worries mate!
91 while ((iTotal < 1) && (iResult != -1))
93 iResult = recv(m_iSock, temp, 1, 0);
98 perror("IoTSocketServer: Receive data error!");