-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
81 lines (64 loc) · 2.33 KB
/
client.cpp
File metadata and controls
81 lines (64 loc) · 2.33 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
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <chrono>
int main(int argc, char *argv[]) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " ip_address port" << std::endl;
exit(1);
}
const char *serverIp = argv[1];
int port = std::atoi(argv[2]);
char msg[2000];
struct sockaddr_in sendSockAddr;
std::memset(&sendSockAddr, 0, sizeof(sendSockAddr));
sendSockAddr.sin_family = AF_INET;
sendSockAddr.sin_addr.s_addr = inet_addr(serverIp);
sendSockAddr.sin_port = htons(port);
int clientSd = socket(AF_INET, SOCK_STREAM, 0);
if (clientSd == -1) {
std::cerr << "Error creating socket!" << std::endl;
exit(1);
}
if (connect(clientSd, reinterpret_cast<struct sockaddr*>(&sendSockAddr), sizeof(sendSockAddr)) < 0) {
std::cerr << "Error connecting to socket!" << std::endl;
exit(1);
}
std::cout << "Connected to the server!" << std::endl;
int bytesRead = 0, bytesWritten = 0;
auto start = std::chrono::high_resolution_clock::now();
while (true) {
std::cout << "> ";
std::string data;
std::getline(std::cin, data);
std::memset(msg, 0, sizeof(msg));
std::strcpy(msg, data.c_str());
if (data == "exit") {
send(clientSd, msg, std::strlen(msg), 0);
break;
}
bytesWritten += send(clientSd, msg, std::strlen(msg), 0);
std::cout << "Awaiting server response..." << std::endl;
std::memset(msg, 0, sizeof(msg));
bytesRead += recv(clientSd, msg, sizeof(msg), 0);
if (!std::strcmp(msg, "exit")) {
std::cout << "Server has quit the session" << std::endl;
break;
}
std::cout << "Server: " << msg << std::endl;
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
close(clientSd);
std::cout << "******** Session ********" << std::endl;
std::cout << "Bytes written: " << bytesWritten << " Bytes read: " << bytesRead << std::endl;
std::cout << "Elapsed time: " << elapsed.count() << " seconds" << std::endl;
std::cout << "Connection closed" << std::endl;
return 0;
}