3 #include <sys/socket.h>
10 #include "PlatformException.h"
11 #include "misc/StreamAsString.h"
12 #include "misc/String.h"
17 TCPSocket::TCPSocket(std::string host
, int port
) {
18 std::cout
<< "TCPSocket::TCPSocket(): beginning initialization . . ." << std::endl
;
19 struct addrinfo hints
, *result
;
21 memset(&hints
, 0, sizeof(hints
));
22 hints
.ai_family
= AF_UNSPEC
;
23 hints
.ai_socktype
= SOCK_STREAM
;
24 hints
.ai_flags
= hints
.ai_protocol
= 0;
25 std::cout
<< "TCPSocket::TCPSocket(): resolving address . . ." << std::endl
;
26 int ret
= getaddrinfo(host
.c_str(), Misc::String::from
<int>(port
).c_str(), &hints
, &result
);
28 throw PlatformException(Misc::StreamAsString() << "Couldn't resolve hostname: " << gai_strerror(ret
), false);
31 if(result
->ai_next
!= NULL
) {
32 std::cout
<< "Warning: Hostname \"" << host
<< "\" resolves to multiple IPs. Using the first." << std::endl
;
36 std::cout
<< "TCPSocket::TCPSocket(): creating socket . . ." << std::endl
;
37 socket_fd
= socket(result
->ai_family
, result
->ai_socktype
, result
->ai_protocol
);
38 if(socket_fd
== -1) throw PlatformException("Couldn't create socket: ");
40 std::cout
<< "TCPSocket::TCPSocket(): connecting socket . . ." << std::endl
;
41 std::cout
<< "TCPSocket::TCPSocket(): socket_fd is: " << socket_fd
<< std::endl
;
42 std::cout
<< "TCPSocket::TCPSocket(): result->ai_addr is: " << result
->ai_addr
<< std::endl
;
43 if(connect(socket_fd
, result
->ai_addr
, result
->ai_addrlen
) == -1) throw PlatformException("Couldn't connect to host: ");
45 std::cout
<< "Connected successfully!" << std::endl
;
47 /* Socket is now connected. */
50 TCPSocket::~TCPSocket() {
54 void TCPSocket::send_data(std::string data
) {
57 raw_data
= Misc::StreamAsString() << htons(data
.length()) << data
;
59 int sent
= write(socket_fd
, raw_data
.c_str(), raw_data
.length());
60 if(sent
== -1) valid
= false;
62 std::string
TCPSocket::get_data() {
63 if(!is_valid()) return "";
65 read(socket_fd
, &size
, 2);
72 int ret
= read(socket_fd
, &c
, 1);
74 if(errno
== EAGAIN
) continue;
87 } // namespace Platform
88 } // namespace Aesalon