在很多時候需要在網絡上發送string 使用過的協議為UDP ,這裡小編 使用boost 官方的UDP 庫封裝了,一個對象用於發送。十分方便。
上代碼 ,如下:
StringQueue的封裝。 加入了互斥鎖,使用簡單的變量Lock 實現,簡單易懂。
String 的隊列 對象包含進隊出隊,自鎖等等操作。
頭文件:
[plain] #include <iostream>
#include <list>
using namespace std ;
class StringQueue
{
public:
bool Lock;
list<string> Data ;
StringQueue():Lock(0){}
~StringQueue(){}
void Lockdata();
void UnLockdata();
void WaitUnLock();
private:
protected:
};
#include <iostream>
#include <list>
using namespace std ;
class StringQueue
{
public:
bool Lock;
list<string> 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 <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <list>
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 <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <list>
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;
}