asio(十)、udp服务器

该代码示例展示如何使用Boost.ASIO库创建一个简单的UDP服务器,它监听端口13,接收来自客户端的请求,并发送当前日期和时间作为响应。主要涉及的关键函数有socket.receive_from()和socket.send_to()。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官网教程:https://think-async.com/Asio/asio-1.26.0/doc/asio/tutorial/tutdaytime5.html

udp服务器

int main()
{
  try
  {
    asio::io_context io_context;

创建一个ip::udp::socket对象以接收udp端口13上的请求。

   udp::socket socket(io_context, udp::endpoint(udp::v4(), 13));

等待客户端启动与我们的联系。remote_endpoint对象将由ip::udp::socket::receive_from()填充。

    for (;;)
    {
      boost::array<char, 1> recv_buf;
      udp::endpoint remote_endpoint;
      socket.receive_from(asio::buffer(recv_buf), remote_endpoint);

确定我们要发送给客户的内容。

 std::string message = make_daytime_string();

将响应发送到remote_endpoint。

      asio::error_code ignored_error;
      socket.send_to(asio::buffer(message),
          remote_endpoint, 0, ignored_error);
    }
  }

最后,处理任何异常。

  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <asio.hpp>

using asio::ip::udp;

std::string make_daytime_string()
{
  using namespace std; // For time_t, time and ctime;
  time_t now = time(0);
  return ctime(&now);
}

int main()
{
  try
  {
    asio::io_context io_context;

    udp::socket socket(io_context, udp::endpoint(udp::v4(), 13));

    for (;;)
    {
      boost::array<char, 1> recv_buf;
      udp::endpoint remote_endpoint;
      socket.receive_from(asio::buffer(recv_buf), remote_endpoint);

      std::string message = make_daytime_string();

      asio::error_code ignored_error;
      socket.send_to(asio::buffer(message),
          remote_endpoint, 0, ignored_error);
    }
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值