Began switching the GUI system to use a QSettings object.
[aesalon.git] / src / platform / TCPSocket.cpp
bloba5aff0e0d2a0f8aefd3137c93bfd3eb7b314b444
1 #include <iostream>
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <arpa/inet.h>
5 #include <netdb.h>
6 #include <cstring>
7 #include <errno.h>
9 #include "TCPSocket.h"
10 #include "PlatformException.h"
11 #include "misc/StreamAsString.h"
12 #include "misc/String.h"
14 namespace Aesalon {
15 namespace Platform {
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);
27 if(ret != 0) {
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. */
48 valid = true;
50 TCPSocket::~TCPSocket() {
51 close(socket_fd);
54 void TCPSocket::send_data(std::string data) {
55 std::string raw_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 "";
64 uint16_t size;
65 read(socket_fd, &size, 2);
66 size = ntohs(size);
68 std::string data;
70 while(size) {
71 char c;
72 int ret = read(socket_fd, &c, 1);
73 if(ret == -1) {
74 if(errno == EAGAIN) continue;
75 else {
76 valid = false;
77 break;
80 data += c;
81 size --;
84 return data;
87 } // namespace Platform
88 } // namespace Aesalon