/** * @file include/di/TCPClient.h * @brief Generic TCP client * @date April 28, 2015 * @author R.W.A. van der Heijden & J.J.J. Jacobs * @copyright 2015 Dual Inventive Technology Centre B.V. * * Generic TCP client which resolves and connect to a TCP socket */ #ifndef INCLUDE_DI_TCPCLIENT_H_ #define INCLUDE_DI_TCPCLIENT_H_ #include #include #include #include namespace Di { /** * @class TCPClient * * Generic TCP client, connects to hostname and port */ class TCPClient { public: enum SelectResult { SELECT_TIMEOUT, SELECT_READ, SELECT_ERROR }; /** * Constructor, expects a string in the format: "host:port" */ explicit TCPClient(std::string hostport); /** * Constructor, resolves and connects to host:port */ TCPClient(std::string host, unsigned int port); /** * Destructor, also closes the connection when needed */ ~TCPClient(void); /** * Send data to the socket * @param data Data to send over the socket * @return -1 on failure or when connection is closed, else number of bytes written */ ssize_t send(const std::string &data); ssize_t send(const char *data, size_t len); ssize_t sendLine(std::string data); #ifdef DI_BUFFER_DECL ssize_t send(const struct di_buffer &buf) { return send(reinterpret_cast(buf.data), buf.used); } ssize_t send(const struct di_buffer *buf) { return send(reinterpret_cast(buf->data), buf->used); } #endif ssize_t read(uint8_t *buffer, size_t maxReadSize); #ifdef DI_BUFFER_DECL ssize_t read(struct di_buffer *buf) { auto ret = read(buf->cur, buf->size - buf->used); if (ret > 0) { buf->used += static_cast(ret); buf->cur = &buf->data[buf->used]; } return ret; } #endif ssize_t readByte(char *buf); ssize_t readLine(std::shared_ptr buffer); enum SelectResult selectIn(std::chrono::system_clock::duration to); enum SelectResult selectIn(size_t timeoutMs); bool connected(void); /** * Connect to __host:__port */ void connect(void); /** * Disconnect from host (when connected) */ void disconnect(void); private: std::string __host; //!< Hostname of server unsigned int __port; //!< Port of server bool __connected; //!< Boolean whether we are connected or not int __sockfd; //!< Socket FD }; } // namespace Di #endif // INCLUDE_DI_TCPCLIENT_H_