标签:boost asio
Boost Asio 网络编程 基本用法boost::asio::ip::address addr; addr = addr.from_string("127.0.0.1"); assert(addr.is_v4()); OutputDebugStringA(addr.to_string().c_str()); addr = addr.from_string("1000:0000:0000:0000:0000:1234:5678:1234"); assert(addr.is_v6()); OutputDebugStringA(addr.to_string().c_str());
boost::asio::ip::address addr; addr = addr.from_string("127.0.0.1"); boost::asio::ip::tcp::endpoint ep(addr, 1234); //构造一个endpoint ep.address() 获取IP地址 ep.port() 获取端口号
头文件
#pragma once #include <boost/asio.hpp> #include <boost/array.hpp> #include <boost/bind.hpp> #include <string> class CASIOClient { public: CASIOClient(const std::string & hostname,boost::asio::io_service& io_service_); ~CASIOClient(void); private: boost::asio::ip::tcp::socket m_Sock; boost::asio::ip::tcp::resolver m_Resolver; boost::array<char, 4096> buffer; void receive_handler(const boost::system::error_code &ec, std::size_t bytes_transferred); void connect_handler(const boost::system::error_code &ec); void resolve_handler(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it); };
实现文件
#include "StdAfx.h" #include "ASIOClient.h" CASIOClient::CASIOClient( const std::string& hostname, boost::asio::io_service& io_service_) : m_Resolver(io_service_), m_Sock(io_service_) { boost::asio::ip::tcp::resolver::query query(hostname,"http"); m_Resolver.async_resolve(query,boost::bind( &CASIOClient::resolve_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); } CASIOClient::~CASIOClient(void) { } void CASIOClient::receive_handler(const boost::system::error_code &ec, std::size_t bytes_transferred) { if (!ec) { OutputDebugStringA(std::string(buffer.data(), bytes_transferred).c_str()); m_Sock.async_read_some(boost::asio::buffer(buffer), boost::bind(&CASIOClient::receive_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void CASIOClient::connect_handler(const boost::system::error_code &ec) { if (!ec) { m_Sock.write_some(boost::asio::buffer("GET http://www.boost.org/LICENSE_1_0.txt HTTP 1.0\r\nHost:http://www.boost.org\r\n\r\n")); m_Sock.async_read_some(boost::asio::buffer(buffer), boost::bind(&CASIOClient::receive_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void CASIOClient::resolve_handler(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it) { if (!ec) { m_Sock.async_connect(*it,boost::bind(&CASIOClient::connect_handler,this, boost::asio::placeholders::error)); } }
调用
boost::asio::io_service io_service; CASIOClient client("www.boost.org",io_service); io_service.run();
异步方式的函数前面都有async_前缀,函数参数中其中一个是回调函数
以上程序在VC2010下编译通过
标签:boost asio
原文地址:http://blog.csdn.net/flyfish1986/article/details/43672801