-
Packet Queue Example CodeC++ 2014. 2. 20. 06:36
################## PacketBuffer.h
template <typename T>
class PacketBuffer
{
private:
std::queue<T> mPackets;
int mMaxSize;
public:
PacketBuffer(size_t maxSize=0);
virtual ~PacketBuffer(void);
bool bufferPacket(const T& packet);
T& getNextPacket();
};
template <typename T>
PacketBuffer<T>::PacketBuffer(size_t maxSize) : mMaxSize(maxSize)
{
}
template <typename T>
PacketBuffer<T>::~PacketBuffer(void)
{
}
template <typename T>
bool PacketBuffer<T>::bufferPacket(const T& packet)
{
if (mMaxSize > 0 && mPackets.size() == mMaxSize ) {
return false;
}
mPackets.push(packet);
return true;
}
template <typename T>
T& PacketBuffer<T>::getNextPacket() throw (std::out_of_range)
{
if (mPackets.empty()) {
throw std::out_of_range("no packet in buffer");
}
T packet = mPackets.front(); // Read a last data from front.
mPackets.pop(); // Remove the last data
return packet;
}
####################### main.cpp
typedef struct {
int id;
char data[1000];
int checksum;
} tcp_packet;
PacketBuffer<tcp_packet> pb;
// PacketBuffer<tcp_packet> pb(3);
tcp_packet packet1 = {1,"welcome ", 3};
if (!pb.bufferPacket(packet1))
cout << "Queue Full";
tcp_packet packet2 = {2,"to ", 3};
pb.bufferPacket(packet2);
tcp_packet packet3 = {3,"korea ", 3};
pb.bufferPacket(packet3);
tcp_packet packet4 = {4,"!! ", 3};
pb.bufferPacket(packet4);
while (true) {
try {
tcp_packet p1 = pb.getNextPacket();
cout << "packet "<< p1.data << endl;
}
catch (const std::out_of_range) {
cout << "queue empty" << endl;
break;
}
}
}
'C++' 카테고리의 다른 글
MultiMap (0) 2014.02.22 STL map 의 정리 (0) 2014.02.20 Round Robin Queue를 이용한 Process Scheduler (0) 2014.02.19 Vector constructor and descructor (0) 2014.02.17 STL Container 선택 (0) 2014.02.17