#ifndef UDP_HPP_
#define UDP_HPP_
//udp接收消息
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <thread>
#include <chrono>
#include <map>
#include <string>
#include <functional>
#include <mutex>
#include <thread>
#include <chrono>
#include <atomic>
namespace tzm {
class UDPReceive
{
public:
UDPReceive():
initialized_(false)
{
};
int Initialize(int port)
{
{
socket_descriptor_ = socket(AF_INET,SOCK_DGRAM,0);
if(socket_descriptor_ == -1)
{
printf("open socket failed ! error message : %s\n",strerror(errno));
return -1;
}
port_ = port;
bzero(&sin_,sizeof(sin_));
sin_.sin_family = AF_INET;
sin_.sin_addr.s_addr = htonl(INADDR_ANY);
sin_.sin_port = htons(port_);
sin_len_ = sizeof(sin_);
if(bind(socket_descriptor_,(struct sockaddr *)&sin_,sizeof(sin_))==-1)
{
printf("bind IP failed ! error message : %s\n",strerror(errno));
return -1;
}
printf("UDP Port: %d initialized_! \n",port_);
}
initialized_ = true;
receive_thread_ = new std::thread(std::bind(&UDPReceive::__Start,this));
}
int Release()
{
initialized_ = false;
receive_thread_->join();
if(receive_thread_)
{
delete receive_thread_;
receive_thread_ = nullptr;
}
port_ = -1;
};
int RegistorCallback(const std::string& str,std::function<int()> callback)
{
std::unique_lock<std::mutex> lock(callback_mutex_);
callbacks_.insert(make_pair(str,callback));
};
private:
int __Start()
{
if(initialized_)
{
do
{
if(recvfrom(socket_descriptor_,message_buff_,sizeof(message_buff_),0,(struct sockaddr *)&sin_,&sin_len_)!=1)
{
{
std::unique_lock<std::mutex> lock(callback_mutex_);
for(auto &pair:callbacks_)
{
if(strncmp(message_buff_,pair.first.c_str(),pair.first.size()) == 0)
{
std::function<int()> callback = pair.second;
callback();
}
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}while(initialized_);
}
};
std::thread* receive_thread_ = nullptr;
std::atomic_bool initialized_;
int port_=-1;
int socket_descriptor_;
socklen_t sin_len_;
struct sockaddr_in sin_;
char message_buff_[256];
std::map<std::string, std::function<int()>> callbacks_;
std::mutex callback_mutex_;
};
}//namespace positec
#endif //UDP_HPP_
UDP socket 字符串响应类
最新推荐文章于 2024-06-07 09:53:03 发布