-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStopAndWait.cpp
More file actions
72 lines (65 loc) · 1.49 KB
/
StopAndWait.cpp
File metadata and controls
72 lines (65 loc) · 1.49 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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// Sender class
class Sender
{
public:
int message;
bool ackReceived;
Sender(int m) : message(m), ackReceived(false) {}
bool isAckReceived() { return ackReceived; }
void send()
{
cout << "Sender: Sending message " << message << endl;
srand(time(0));
int chance = rand() % 2; // 0 or 1
if (chance)
{
cout << "Receiver: Message received." << endl;
ackReceived = true;
}
else
{
cout << "Receiver: Message lost." << endl;
ackReceived = false;
}
}
};
// Receiver class
class Receiver
{
public:
int message;
bool ackSent;
Receiver() : message(0), ackSent(false) {}
void receive(Sender &sender)
{
cout << "Receiver: Receiving message." << endl;
message = sender.isAckReceived() ? sender.message + 1 : sender.message;
cout << "Receiver: Sending acknowledgement." << endl;
ackSent = true;
}
bool isAckSent() { return ackSent; }
};
int main()
{
Sender sender(1);
Receiver receiver;
while (true)
{
sender.send();
receiver.receive(sender);
if (receiver.isAckSent() && sender.isAckReceived())
{
cout << "Sender: Acknowledgement received." << endl;
break;
}
else
{
cout << "Sender: Resending message." << endl;
}
}
return 0;
}