Boost的UDP接收server示例


废话不多说直接上代码:


GetConfig函数见本栏其他文章。功能:读取文本配置。

#include <sys/wait.h>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include "boost/bind.hpp"





class receiver_
{
public:
  receiver_(boost::asio::io_service& io_service,
      const boost::asio::ip::address& listen_address,
      const boost::asio::ip::address& multicast_address,string src_port)
    : socket_(io_service),
      timer_(io_service)
  {
    // Create the socket so that multiple may be bound to the same address.
	  stringstream buffer ; buffer<<src_port ; int PORT = 0 ;
	  buffer>>PORT;
    boost::asio::ip::udp::endpoint listen_endpoint(
        listen_address, PORT);
    socket_.open(listen_endpoint.protocol());
    socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
    socket_.bind(listen_endpoint);

    // Join the multicast group.
    socket_.set_option(
        boost::asio::ip::multicast::join_group(multicast_address));


    timer_.expires_from_now(boost::posix_time::seconds(1));
    timer_.async_wait(
        boost::bind(&receiver_::handle_timeout, this,
          boost::asio::placeholders::error));


  }

  void handle_receive_from(const boost::system::error_code& error,
      size_t bytes_recvd)
  {
    if (!error)
    {
    	printf("Data has coming \n");
    	int rtn ;
    	int pid=fork() ;
    	if ( pid == 0 ) {
    		/* 子进程程序 */
        	this->timer_.cancel();
    		ReadTrackMSGBuf(data_,bytes_recvd);
        	exit(1);
    	}
    	else {
    		/* 父进程程序*/
			printf("Father waiting \n");
//			signal(SIGCHLD,SIG_IGN);
			waitpid(pid,&rtn,0);
//			wait(pid);
			printf("Child Back\n");
    	}
    }
    else{
    	Fprint_String(error.message().c_str(),"StdTrackError","a++");
    }
  }
  void handle_timeout(const boost::system::error_code& error)
  {
    if (!error)
    {
        memset(data_,0,max_length);

    	socket_.async_receive_from(
            boost::asio::buffer(data_, max_length), sender_endpoint_,
            boost::bind(&receiver_::handle_receive_from, this,
              boost::asio::placeholders::error,
              boost::asio::placeholders::bytes_transferred));

      timer_.cancel();
      timer_.expires_from_now(boost::posix_time::milliseconds(100));
      timer_.async_wait(
          boost::bind(&receiver_::handle_timeout, this,
            boost::asio::placeholders::error));

    }
    else{
    	Fprint_String(error.message().c_str(),"StdTrackError","a++");
    }
  }

private:
  boost::asio::deadline_timer timer_;
  boost::asio::ip::udp::socket socket_;
  boost::asio::ip::udp::endpoint sender_endpoint_;
  enum { max_length = 102400 };
  char data_[max_length];
};

int main_UDP_Receive()
{
  try
  {
    boost::asio::io_service io_service;

    char *Addr = GetConfigVal("TrackConfig","SourceAddr");
    char *Port = GetConfigVal("TrackConfig","SourcePort");
    if(Addr==NULL || Port==NULL)
    {
    	printf("TrackConfig Lost\n");
    	Fprint_String("TrackConfig Lost\n","StdTrackError","a+");
    	exit(-1);
    }
    string StrAddr(Addr); string StrPort(Port); free(Addr); free(Port);

	receiver_ r(io_service,
		boost::asio::ip::address::from_string("0.0.0.0"),
		boost::asio::ip::address::from_string(StrAddr.c_str()),StrPort.c_str());
	io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}







以下是一个使用Boost.Asio库创建UDP服务器和客户端的Demo,使用Qt编写: ```c++ #include <QCoreApplication> #include <QDebug> #include <boost/asio.hpp> using boost::asio::ip::udp; class UdpServer { public: UdpServer(boost::asio::io_context& io_context, short port) : socket_(io_context, udp::endpoint(udp::v4(), port)) { StartReceive(); } private: void StartReceive() { socket_.async_receive_from( boost::asio::buffer(recv_buffer_), remote_endpoint_, [this](boost::system::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd > 0) { qDebug() << "Received message: " << QString::fromStdString(std::string(recv_buffer_.begin(), recv_buffer_.begin() + bytes_recvd)); StartReceive(); } }); } udp::socket socket_; udp::endpoint remote_endpoint_; std::array<char, 1024> recv_buffer_; }; class UdpClient { public: UdpClient(boost::asio::io_context& io_context, const std::string& host, short port) : socket_(io_context, udp::endpoint(udp::v4(), 0)) , remote_endpoint_(boost::asio::ip::address::from_string(host), port) { StartSend(); } void StartSend() { std::string message = "Hello, world!"; socket_.async_send_to(boost::asio::buffer(message), remote_endpoint_, [this](boost::system::error_code ec, std::size_t /*bytes_sent*/) { if (!ec) { qDebug() << "Sent message: " << QString::fromStdString(message); } StartSend(); }); } private: udp::socket socket_; udp::endpoint remote_endpoint_; }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); boost::asio::io_context io_context; UdpServer server(io_context, 12345); UdpClient client(io_context, "127.0.0.1", 12345); io_context.run(); return a.exec(); } ``` 在此示例中,我们创建了一个UDP服务器和一个UDP客户端,它们都使用Boost.Asio库进行异步通信。服务器监听本地端口12345并在接收到消息后立即发送回复,客户端发送“Hello,world!”消息到服务器并等待回复。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值