C++封装的链表UDP发送器

2014-11-24 01:44:13 · 作者: · 浏览: 2


在很多时候需要在网络上发送string 使用过的协议为UDP ,这里小编 使用boost 官方的UDP 库封装了,一个对象用于发送。十分方便。

上代码 ,如下:


StringQueue的封装。 加入了互斥锁,使用简单的变量Lock 实现,简单易懂。

String 的队列 对象包含进队出队,自锁等等操作。


头文件:

[plain] #include
#include
using namespace std ;


class StringQueue
{
public:
bool Lock;
list Data ;

StringQueue():Lock(0){}
~StringQueue(){}

void Lockdata();
void UnLockdata();
void WaitUnLock();
private:

protected:

};

#include
#include
using namespace std ;


class StringQueue
{
public:
bool Lock;
list Data ;

StringQueue():Lock(0){}
~StringQueue(){}

void Lockdata();
void UnLockdata();
void WaitUnLock();
private:

protected:

};

String Queue的CPP文件:


[plain] void StringQueue::Lockdata()
{
printf("Queue String Locked\n");
this->Lock = 1 ;
}
void StringQueue::UnLockdata()
{
printf("Queue String UnLocked\n");
this->Lock = 0 ;
}
void StringQueue::WaitUnLock()
{
while(this->Lock==1)
{
printf("Queue String Waiting\n");
usleep(200000);
}
printf("Queue String UnLocked\n");
}

void StringQueue::Lockdata()
{
printf("Queue String Locked\n");
this->Lock = 1 ;
}
void StringQueue::UnLockdata()
{
printf("Queue String UnLocked\n");
this->Lock = 0 ;
}
void StringQueue::WaitUnLock()
{
while(this->Lock==1)
{
printf("Queue String Waiting\n");
usleep(200000);
}
printf("Queue String UnLocked\n");
}

接下来说明UDP的发送对象了,他根据boost 官方的发送示例更改,十分方便易用,boost 又有很强的移植性,linux ,windows 等系统均可使用


废话不多少,代码如下:


头文件:

[plain] #include
#include
#include
#include
using namespace std ;

typedef unsigned int uint ;


class UDPSender
{
public:
UDPSender(StringQueue Data,string DspthDst,string DspPort);

~UDPSender(){}
int main_UDP_Send(char *Data,uint Len,char *UDPdst, char *port);
private:
StringQueue &Data_;
protected:

};

#include
#include
#include
#include
using namespace std ;

typedef unsigned int uint ;


class UDPSender
{
public:
UDPSender(StringQueue Data,string DspthDst,string DspPort);

~UDPSender(){}
int main_UDP_Send(char *Data,uint Len,char *UDPdst, char *port);
private:
StringQueue &Data_;
protected:

};

CPP文件:

[plain] UDPSender::UDPSender(StringQueue Data,string DspthDst,string DspPort):Data_(Data)
{

while(Data_.Data.size()>0)
{
printf("!!!!!!! UDP sending %d",Data_.Data.size());
string Sendbuffer = Data.Data.front();
main_UDP_Send((char*)Sendbuffer.c_str(),Sendbuffer.length(),(char*)DspthDst.c_str(),(char*)DspPort.c_str());
Data.Data.pop_front();
}

}
int UDPSender::main_UDP_Send(char *Data,uint Len,char *UDPdst, char *port)
{
try
{
boost::asio::io_service io_service;

udp::socket s(io_service, udp::endpoint(udp::v4(), 0));

udp::resolver resolver(io_service);
udp::resolver::query query(udp::v4(),UDPdst,port);
udp::resolver::iterator iterator = resolver.resolve(query);

s.send_to(boost::asio::buffer(Data, Len), *iterator);

}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}

return 0;
}