From 14d91d34063a221360fed3ef76e8baee58eb7922 Mon Sep 17 00:00:00 2001 From: Kshitij Date: Wed, 25 Sep 2024 22:18:20 +0530 Subject: [PATCH] added code for sliding window, in testing phase --- Codes/sliding-window.cpp | 64 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Codes/sliding-window.cpp diff --git a/Codes/sliding-window.cpp b/Codes/sliding-window.cpp new file mode 100644 index 0000000..3b2efec --- /dev/null +++ b/Codes/sliding-window.cpp @@ -0,0 +1,64 @@ +#include +#include +#include + +using namespace std; + +const int WINDOW_SIZE = 5; // size of the sliding window + +class SlidingWindow { +private: + vector 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; +}