-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClient.h
More file actions
92 lines (72 loc) · 2.91 KB
/
Client.h
File metadata and controls
92 lines (72 loc) · 2.91 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
89
90
#pragma once
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include "NodeManager.h"
#include <vector>
#include <sys/types.h> //socket, bind
#include <sys/socket.h> //coket, bind, listen, inet_ntoa
#include <netinet/in.h> //hton1, htons, inet_ntoa
#include <unistd.h> // for close()
#include <arpa/inet.h>
#include <chrono>
#include <thread>
using namespace std;
using namespace chrono;
class Client{
public:
void clientConnect(const char *server, int serverPort){
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket < 0){
cerr << "Client Socket Creation Failed\n";
}
// set up server structure
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(server);
serverAddress.sin_port = htons(serverPort);
if(connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0){
cerr << "Connection Failed\n";
}
srand(time(0));
// chrnon used to see how long execution took
auto start = high_resolution_clock::now();
for(int i = 0; i < 50; i++){
//read transaction choices from buffer
char choice[1024] = {0};
read(clientSocket, choice, sizeof(choice));
cout << choice << "\n";
//client will send a random transaction between 1 - 4
int randomNumber = rand() % 4 + 1;
string userChoice = to_string(randomNumber) + '\n';
cout << "now sending clients choice\n";
// send that choice to server
send(clientSocket, userChoice.c_str(), userChoice.size(), 0);
cout << "Choice sent to server " << userChoice << endl;
//this_thread::sleep_for(chrono::seconds(1));
while(true){
char buffer[1024] = {0};
//recieve response/ack from server that they recived that choice
read(clientSocket, buffer, sizeof(buffer));
cout << "Response from server " << buffer << endl;
// If transaction complete then break
if(strstr(buffer, "Transaction Complete\n")){
break;
}
else{
// then client also sends response to ack which allows the
// second hop to happen
string res = "OK\n";
send(clientSocket, res.c_str(), res.size(), 0);
cout << "Sending response: " << res << endl;
}
}
}
auto end = high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(end-start);
cout << "Time taken: " << duration.count() << " Milliseconds \n";
// close socket connection
close(clientSocket);
}
};