-
Notifications
You must be signed in to change notification settings - Fork 0
/
classClient.cpp
87 lines (71 loc) · 1.93 KB
/
classClient.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "classClient.h"
TCPClient::TCPClient(char *port)
{
configConnection(port, LOCAL_HOST);
}
TCPClient::TCPClient(char *port,char *server)
{
configConnection(port, server);
}
TCPClient::~TCPClient()
{
freeaddrinfo(host);
close(sockfd);
}
void TCPClient::configConnection(char *port, char *server){
//Init the struct hint with zero
memset(&hint, 0, sizeof(hint));
//Configure connection
hint.ai_family = AF_INET; /* IPv4 */
hint.ai_socktype = SOCK_STREAM; /* TCP */
//Config host structure for socket connection
addsockfd = getaddrinfo(server, port, &hint, &host);
if (NETDB_SUCCESS != addsockfd){
perror("failed");
exit(1);
}// Server found
//Create socket
sockfd = socket(host->ai_family,
host->ai_socktype,
host->ai_protocol);
//Verify endpoit file descriptor
if (SOCKETFD_FAILED == sockfd){
perror("failed");
exit(1);
}
}
void TCPClient::connectInit(void){
//Init socket connection
addsockfd = connect(sockfd,
host->ai_addr,
host->ai_addrlen);
//Connection stablish
if(SOCKCONNEC_FAILED == addsockfd){
perror("failed");
exit(1);
}
}
std::string TCPClient::sreadValue(void){
std::string sbuffer(BUFSIZ, 0);
std::string tmp {0};
//Read socket buffer
addsockfd = recv(sockfd,
sbuffer.data(),
BUFSIZ,
0);
if(addsockfd < 1)
{
//close connection to client
close(sockfd);
//return in case
tmp = "++";
}
else{
//Create an istringstream object and initialize it with the buffer
std::istringstream isss(sbuffer.data());
//parsed data
//extracts the available value from the stream and assigns it to num
isss >> tmp;
}
return tmp;
}