added code for sliding window, in testing phase

This commit is contained in:
K 2024-09-25 22:18:20 +05:30
parent 1c3e9f70b1
commit 14d91d3406
Signed by: notkshitij
GPG Key ID: C5B8BC7530F8F43F

64
Codes/sliding-window.cpp Normal file
View File

@ -0,0 +1,64 @@
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int WINDOW_SIZE = 5; // size of the sliding window
class SlidingWindow {
private:
vector<int> sent_frames; // queue of sent frames
int next_frame_to_send; // index of the next frame to send
int next_frame_to_receive; // index of the next frame to receive
public:
SlidingWindow() : next_frame_to_send(0), next_frame_to_receive(0) {}
// send a frame
void send_frame(int frame_number) {
if (sent_frames.size() < WINDOW_SIZE) {
sent_frames.push_back(frame_number);
next_frame_to_send++;
cout << "Sent frame " << frame_number << endl;
} else {
cout << "Window is full, cannot send frame " << frame_number << endl;
}
}
// receive a frame
void receive_frame(int frame_number) {
if (frame_number == next_frame_to_receive) {
next_frame_to_receive++;
cout << "Received frame " << frame_number << endl;
} else {
cout << "Received frame " << frame_number << ", but expected frame " << next_frame_to_receive << endl;
}
// remove acknowledged frames from the sent_frames queue
while (!sent_frames.empty() && sent_frames.front() <= next_frame_to_receive - 1) {
sent_frames.erase(sent_frames.begin());
}
}
};
int main() {
SlidingWindow window;
// send some frames
window.send_frame(0);
window.send_frame(1);
window.send_frame(2);
window.send_frame(3);
window.send_frame(4);
window.send_frame(5);
// receive some frames
window.receive_frame(0);
window.receive_frame(1);
window.receive_frame(2);
window.receive_frame(3);
window.receive_frame(4);
return 0;
}