This tutorial program shows how to use asio to implement a client application with UDP. 
本例示范如何使用Asio实现一个UDP客户端程序。
 #include <iostream>
#include <iostream>
 #include <boost/array.hpp>
#include <boost/array.hpp>
 #include <boost/asio.hpp>
#include <boost/asio.hpp>

 using boost::asio::ip::udp;
using boost::asio::ip::udp; 
The start of the application is essentially the same as for the TCP daytime client. 
 应用程序的开始部分同TCP daytime客户端在本质上是相同的。
int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: client <host>" << std::endl;
      return 1;
    }
    boost::asio::io_service io_service;
 
We use an boost::asio::ip::udp::resolver object to find the correct remote endpoint to use based on the host and service names. The query is restricted to return only IPv4 endpoints by the boost::asio::ip::udp::v4() argument. 
我们使用boost::asio::ip::udp::resolver对象来找到正确的基于主机和服务器名称的远程终端。使用boost::asio::ip::udp::v4()参数来限制query 仅仅返回IPv4的节点。
 udp::resolver resolver(io_service);
    udp::resolver resolver(io_service);
 udp::resolver::query query(udp::v4(), argv[1], "daytime");
    udp::resolver::query query(udp::v4(), argv[1], "daytime"); 
The boost::asio::ip::udp::resolver::resolve() function is guaranteed to return at least one endpoint in the list if it does not fail. This means it is safe to dereference the return value directly. 
如果函数没有失败,boost::asio::ip::udp::resolver::resolve() 保证至少返回列表中一个节点。这意味着直接解引用(提领)返回值是安全的。
 udp::endpoint receiver_endpoint = *resolver.resolve(query);
    udp::endpoint receiver_endpoint = *resolver.resolve(query); 
Since UDP is datagram-oriented, we will not be using a stream socket. Create an boost::asio::ip::udp::socket and initiate contact with the remote endpoint. 
由于UDP(UDP不就是用户数据报协议嘛)是基于数据报的,我们并不需要使用一个基于流的socket。创建一个boost::asio::ip::udp::socket后即可启动同远程终端的连接。
    udp::socket socket(io_service);
    socket.open(udp::v4());
    boost::array<char, 1> send_buf  = { 0 };
    socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);
 
Now we need to be ready to accept whatever the server sends back to us. The endpoint on our side that receives the server's response will be initialised by boost::asio::ip::udp::socket::receive_from(). 
现在,我们需要接收服务器发给我们的任何信息。接收服务器响应的客户端节点将由boost::asio::ip::udp::socket::receive_from()启动。
    boost::array<char, 128> recv_buf;
    udp::endpoint sender_endpoint;
    size_t len = socket.receive_from(
        boost::asio::buffer(recv_buf), sender_endpoint);
    std::cout.write(recv_buf.data(), len);
  }
 
Finally, handle any exceptions that may have been thrown. 
最后,处理可能抛出的任何异常。
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }
  return 0;
}
 
See the full source listing 
全部源码:
	posted on 2008-04-21 09:10 
王晓轩 阅读(3511) 
评论(2)  编辑 收藏 引用  所属分类: 
C\C++