-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathEchoClient.cpp
More file actions
88 lines (70 loc) · 2.16 KB
/
EchoClient.cpp
File metadata and controls
88 lines (70 loc) · 2.16 KB
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
/*
* EchoClient.cpp
*
* Created on: Jan 28, 2016
* Author: Saman Barghi
*/
#include <uThreads/uThreads.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[]){
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <Server Port>" << endl;
exit(1);
}
uint clientPort = atoi(argv[1]);
struct sockaddr_in server;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(clientPort );
std::string msg;
std::vector<char> reply(1025);
int res, count = 0;
try{
Connection cconn(AF_INET , SOCK_STREAM , 0);
if(cconn.connect((struct sockaddr *)&server, sizeof(server)) < 0){
cerr << "Failed to connect to the server! : " << errno << endl;
return 1;
}
for(;;){
count = 0;
cout << "Enter a message (type EXIT to exit):" << endl ;
getline(cin, msg);
if(msg.length() == 0)
continue;
if(msg.compare("EXIT") == 0)
{
cconn.close();
return 0;
}
if(cconn.send(msg.c_str(), msg.length(), 0) < 0){
cerr << "Failed to send the message" << endl;
return 1;
}
while( (res = cconn.recv(reply.data(), reply.size(), 0)) > 0){
for(auto i = reply.begin(); i < reply.begin()+res; i++) cout << *i;
count += res;
if(count >= msg.length())
break;
}
if(res ==0){
cerr << "Server Closed the connection !" << endl;
cconn.close();
return 1;
}
if(res < 0){
cerr << "Failed to receive the message from the server: " << errno << endl;
cconn.close();
return 1;
}
cout << endl;
}
}catch (std::system_error& error){
std::cout << "Error: " << error.code() << " - " << error.what() << endl;
}
return 0;
}