// This file is part of Timmi. // // Timmi is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. #include #include #include #include #include #include TCPClient::TCPClient(): socket_(0) {} TCPClient::~TCPClient() { if (socket_ != 0) { delete socket_; } } bool TCPClient::connect_socket(std::string host, int port) { struct hostent *hostinfo = gethostbyname(host.c_str()); if (hostinfo == NULL) { debug(WARNING, "Resolving hostname failed"); return false; } struct sockaddr_in addr; addr.sin_family = hostinfo->h_addrtype; addr.sin_port = htons(port); memcpy((char *) &addr.sin_addr.s_addr, hostinfo->h_addr_list[0], hostinfo->h_length); int fd = socket(PF_INET, SOCK_STREAM, 0); if (fd < 0) { debug_with_errno(CRITICAL, "Creating socket"); return false; } int status = connect(fd, (struct sockaddr *) &addr, sizeof(addr)); if (status < 0) { debug_with_errno(WARNING, "Connect"); return false; } std::ostringstream hostdesc(""); hostdesc << host << ":" << port; socket_ = new TCPSocket(fd, hostdesc.str()); return true; } bool TCPClient::good() const { return socket_ != NULL && socket_->good(); } bool TCPClient::wait_for_event(int timeout) const { return socket_->wait_for_event(timeout); } void TCPClient::send_line(std::string line) { std::ostringstream msg(""); msg << "Sent line: " << line; debug(VERBOSE, msg.str()); socket_->putline(line); } void TCPClient::handle_line(std::string line) { std::ostringstream msg(""); msg << "Got line: " << line; debug(VERBOSE, msg.str()); } void TCPClient::mainloop() { while (good()) { wait_for_event(); do_main(); } } void TCPClient::do_main() { std::string line(""); while (socket_->getline(line)) { handle_line(line); } }