-
Notifications
You must be signed in to change notification settings - Fork 0
/
TCPClient.cpp
100 lines (93 loc) · 1.89 KB
/
TCPClient.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
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "TCPClient.h"
TCPClient::TCPClient()
{
sock = -1;
port = 0;
address = "";
}
bool TCPClient::setup(string address , int port)
{
if(sock == -1)
{
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
cout << "Could not create socket" << endl;
}
}
if((signed)inet_addr(address.c_str()) == -1)
{
struct hostent *he;
struct in_addr **addr_list;
if ( (he = gethostbyname( address.c_str() ) ) == NULL)
{
herror("gethostbyname");
cout<<"Failed to resolve hostname\n";
return false;
}
addr_list = (struct in_addr **) he->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++)
{
server.sin_addr = *addr_list[i];
break;
}
}
else
{
server.sin_addr.s_addr = inet_addr( address.c_str() );
}
server.sin_family = AF_INET;
server.sin_port = htons( port );
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return false;
}
return true;
}
bool TCPClient::Send(string data)
{
if(sock != -1)
{
if( send(sock , data.c_str() , strlen( data.c_str() ) , 0) < 0)
{
cout << "Send failed : " << data << endl;
return false;
}
}
else
return false;
return true;
}
string TCPClient::receive(int size)
{
char buffer[size];
memset(&buffer[0], 0, sizeof(buffer));
string reply;
if( recv(sock , buffer , size, 0) < 0)
{
cout << "receive failed!" << endl;
return nullptr;
}
buffer[size-1]='\0';
reply = buffer;
return reply;
}
string TCPClient::read()
{
char buffer[1] = {};
string reply;
while (buffer[0] != '\n') {
if( recv(sock , buffer , sizeof(buffer) , 0) < 0)
{
cout << "receive failed!" << endl;
return nullptr;
}
reply += buffer[0];
}
return reply;
}
void TCPClient::exit()
{
close( sock );
}