17 #include <sys/types.h> 19 #include <sys/socket.h> 20 #include <netinet/in.h> 21 #include <netinet/tcp.h> 31 he = gethostbyname(host);
35 std::stringstream msg;
36 msg <<
"gethostbyname(" << host <<
"): " << strerror(errno);
37 cerr << msg.str() << endl;
38 throw std::runtime_error(msg.str().c_str());
40 int sd = socket(PF_INET, SOCK_STREAM, 0);
43 std::stringstream msg;
44 msg <<
"socket: " << strerror(errno);
45 cerr << msg.str() << endl;
46 throw std::runtime_error(msg.str().c_str());
49 far_end.sin_family = AF_INET;
50 far_end.sin_port = htons(port);
51 far_end.sin_addr = *(in_addr*)(he->h_addr);
52 memset(&far_end.sin_zero,
'\0', 8);
53 if (connect(sd, (sockaddr*)&far_end,
sizeof(far_end)) == -1)
55 std::stringstream msg;
56 msg <<
"connect(" << host <<
':' << port <<
"): " << strerror(errno);
57 cerr << msg.str() << endl;
58 throw std::runtime_error(msg.str().c_str());
66 int ret = recv(s, buf, n, 0);
67 while (ret > 0 && total < n)
70 if (buf[total - 1] ==
'\n')
72 ret = recv(s, buf + total, n, 0);
77 int main(
int argc,
char* argv[])
80 char *toks, *itok, *ttag;
82 const char* host =
"localhost";
83 unsigned short port = ~0;
85 int s, ret, queries = 0;
96 if (port <= 1024 || port == (
unsigned short)(~0u))
103 ret = send(s, &
id,
sizeof(
id), 0);
106 const char* msg =
"Could not perform handshake!";
108 throw std::runtime_error(msg);
111 while (getline(std::cin, line))
114 int len = line.size();
115 const char* cstr = line.c_str();
116 const char* sp = strchr(cstr,
' ');
117 ret = send(s, sp + 1, len - (sp + 1 - cstr), 0);
120 const char* msg =
"Could not send unlabeled data!";
122 throw std::runtime_error(msg);
127 const char* msg =
"Could not receive queries!";
129 throw std::runtime_error(msg);
134 ttag = strsep(&toks,
" ");
135 tag = ttag ? std::string(ttag) : std::string(
"'empty");
136 itok = strsep(&toks,
"\n");
137 if (itok ==
nullptr || itok[0] ==
'\0')
143 std::string imp = std::string(itok) +
" " + tag +
" |";
144 pos = line.find_first_of(
'|');
145 line.replace(pos, 1, imp);
148 ret = send(s, cstr, len, 0);
151 const char* msg =
"Could not send labeled data!";
153 throw std::runtime_error(msg);
158 const char* msg =
"Could not receive predictions!";
160 throw std::runtime_error(msg);
164 std::cout <<
"Went through the data by doing " << queries <<
" queries" << endl;
int main(int argc, char *argv[])
int recvall(int s, char *buf, int n)
int open_socket(const char *host, unsigned short port)