(一)IO服务、IO对象基础介绍
// TestBoost.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
/*
* 使用 Boost.Asio 进行异步数据处理:
* (1)I/O 服务:抽象了操作系统的接口,允许第一时间进行异步数据处理
* (2)I/O 对象:则用于初始化特定的操作
*/
#include <boost/asio.hpp>
#include <iostream>
void handler5(const boost::system::error_code& error)
{
std::cout << "定时器5结束返回!" << std::endl;
}
void handler10(const boost::system::error_code& error)
{
std::cout << "定时器10结束返回!" << std::endl;
}
int main()
{
//定义了一个 I/O 服务,所有 I/O 对象通常都需要一个 I/O 服务作为它们的构造函数的第一个参数
boost::asio::io_service io_service;
//定义定时器
boost::asio::deadline_timer timer5(io_service,boost::posix_time::seconds(5));
//启动异步操作 在此不阻塞
timer5.async_wait(handler5);
boost::asio::deadline_timer timer10(io_service, boost::posix_time::seconds(10));
timer10.async_wait(handler10);
//在此阻塞:控制权被操作系统接管定时器结束后调用handler函数
//如果此处不想被阻塞,可以在一个新的线程内部调用 run(),此时会阻塞那个新的线程
//一旦特定的 I/O 服务(io_service)的所有异步操作都完成了,控制权就会返回给 run() 方法
io_service.run();
//以上两个handler分别在5s 10s后执行,然后才run阻塞结束返回main
std::cout << "主程序结束" << std::endl;
}
//运行结果
PS C:\Users\dujinwei\source\repos\TestBoost\Debug> .\TestBoost.exe
定时器5结束返回!
定时器10结束返回!
主程序结束
(二)简单异步网络请求
/*
* 网络编程
* 流程 域名解析->返回解析IP地址->创建连接
*/
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <string>
#include <sstream>
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service); //域名解析句柄
boost::asio::ip::tcp::socket socketIp(io_service); //连接句柄
boost::array<char, 4096> buffer; //缓冲区,接收返回数据
//(3)接受请求返回的数据 bytes_transferred 接收一次数据的大小,接收完所有数据后 read_handler 报错不再执行
void read_handler(const boost::system::error_code& error, std::size_t bytes_transferred)
{
if (!error)
{
std::cout << std::string(buffer.data(), bytes_transferred) << std::endl;
//循环接收数据
socketIp.async_read_some(boost::asio::buffer(buffer), read_handler);
}
}
//(2)创建连接
void connect_handler(const boost::system::error_code& error)
{
if (!error)
{
std::string host = "www.baidu.com";
std::stringstream stream;
stream << "GET https://" << host << " HTTP/1.0\r\n";
stream << "Accept: */*\r\n";
//stream << "Accept-Encoding: gzip, deflate, br\r\n";//不要编码,否则还得多一个解码的步骤
stream << "Accept-Language: zh-Hans-CN, zh-Hans; q=0.8, en-US; q=0.5, en; q=0.3\r\n";
stream << "Connection: Keep-Alive\r\n";
stream << "Host: " << host << "\r\n";
stream << "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134\r\n";
stream << "\r\n";
char buff[1024];
int ret = 0;
ret = snprintf(buff, sizeof(buff), "%s", stream.str().c_str());
boost::asio::write(socketIp, boost::asio::buffer(buff));
socketIp.async_read_some(boost::asio::buffer(buffer), read_handler);
}
}
//(1)域名解析 返回解析后的IP地址供连接使用
void resolve_handler(const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iIp)
{
if (!error)
{
//创建连接 iIp 为域名解析后返回的IP地址
socketIp.async_connect(*iIp, connect_handler);
}
}
int main()
{
//创建一个查询
boost::asio::ip::tcp::resolver::query query("www.baidu.com", "80");
//解析域名 调用resolve_handler
resolver.async_resolve(query, resolve_handler);
io_service.run();
}
//运行结果
PS C:\Users\dujinwei\source\repos\TestBoost\Debug> .\TestBoost.exe
HTTP/1.0 200 OK
Accept-Ranges: bytes
Cache-Control: max-age=1
Content-Length: 7382
Content-Type: text/html
Date: Tue, 07 Sep 2021 13:05:51 GMT
Etag: "1cd6-5480030886bc0"
Expires: Tue, 07 Sep 2021 13:05:52 GMT
Last-Modified: Wed, 08 Feb 2017 07:55:35 GMT
P3p: CP=" OTI DSP COR IVA OUR IND COM "
P3p: CP=" OTI DSP COR IVA OUR IND COM "
Server: Apache
Set-Cookie: BAIDUID=1D94402EBAFCE7B5FE67770DDED0C95E:FG=1; expires=Wed, 07-Sep-22 13:05:51 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1
Set-Cookie: BAIDUID=1D94402EBAFCE7B561CD6D4699CFA9D8:FG=1; expires=Wed, 07-Sep-22 13:05:51 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1
Vary: Accept-Encoding,User-Agent
<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>百度一下,你就知道 </title><style>html{overflow-y:auto}body{font:12px arial;text-align:center;background:#fff}body,p,form,ul{margin:0;padding:0}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}#u{padding:7px 10px 3px 0;text-align:right}#m{width:680px;margin:0 auto}#nv{font-size:16px;margin:0 0 4px;text-align:left;text-indent:117px}#nv a,#nv b,.btn,#lk{font-size:14px}#fm{padding-left:90px;text-align:left}#kw{width:404px;height:22px;padding:4px 7px;padding:6px 7px 2px\9;font:16px arial;background:url(http://www.baidu.com/img/i-1.0.0.png) no-repeat -304px 0;_background-attachment:fixed;border:1px solid #cdcdcd;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.btn{width:95px;height:32px;padding:0;padding-top:2px\9;border:0;background:#ddd url(http://www.baidu.com/img/i-1.0.0.png) no-repeat;cursor:pointer}.btn_h{background-position:-100px 0}#kw,.btn_wr{margin:0 5px 0 0}.btn_wr{width:97px;height:34px;display:inline-block;background:url(http://www.baidu.com/img/i-1.0.0.png) no-repeat -202px 0;_top:1px;*position:relative}#lk{margin:33px 0}#lk span{font:14px "宋体"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}#mCon{height:18px;line-height:18px;position:absolute;right:7px;top:8px;top:10px\9;cursor:pointer;padding:0 18px 0 0;background:url(http://www.baidu.com/img/bg-1.0.0.gif) no-repeat right -134px;background-position:right -136px\9}#mCon span{color:#00c;cursor:default;display:block}#mCon .hw{text-decoration:underline;cursor:pointer}#mMenu{width:56px;border:1px solid #9a99ff;list-style:none;position:absolute;right:7px;top:28px;display:none;background:#fff}#mMenu a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none}#mMenu a:hover{background:#d9e1f6}#mMenu .ln{height:1px;background:#ccf;overflow:hidden;margin:2px;font-size:1px;line-height:1px}#cp,#cp a{color:#77c}#sh{display:none;behavior:url(#default#homepage)}</style></head>
<body><p id="u"><a href="/gaoji/preferences.html">搜索设置</a> | <a href="http://passport.baidu.com/?login&tpl=mn">登录</a></p><div id="m"><p id="lg"><img src="http://www.baidu.com/img/baidu_sylogo1.gif" width="270" height="129" usemap="#mp"></p><p id="nv"><a href="http://news.baidu.com">新 闻</a> <b>网 页</b> <a href="http://tieba.baidu.com">贴 吧</a> <a href="http://zhidao.baidu.com">知 道</a> <a href="http://mp3.baidu.com">MP3</a> <a href="http://image.baidu.com">图 片</a> <a href="http://video.baidu.com">视 频</a> <a href="http://map.baidu.com">地 图</a></p><div id="fm"><form name="f" action="/s"><input type="text" name="wd" id="kw" maxlength="100"><input type="hidden" name="rsv_bp" value="0"><span class="btn_wr"><input type="submit" value="百度一下" id="su" class="btn" onmousedown="this.className='btn btn_h'" onmouseout="this.className='btn'"></span></form><div id="mCon"><span> 输入法</span></div><ul id="mMenu"><li><a href="#" name="ime_hw">手写</a></li><li><a href="#" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="#" name="ime_cl">关闭</a></li></ul></div>
<p id="lk"><a href="http://hi.baidu.com">空间</a> <a href="http://baike.baidu.com">百科</a> <a href="http://www.hao123.com">hao123</a><span> | <a href="/more/">更多&
gt;></a></span></p><p id="lm"></p><p><a id="sh" onClick="this.setHomePage('http://www.baidu.com/')" href="http://utility.baidu.com/traf/click.php?id=215&url=http://www.baidu.com" onmousedown="return ns_c({'fm':'behs','tab':'homepage','pos':0})">把百度设为主页</a></p><p id="lh"><a href="http://e.baidu.com/?refer=888">加入百度推广</a> | <a href="http://top.baidu.com">搜索风云榜</a> | <a href="http://home.baidu.com">关于百度</a> | <a href="http://ir.baidu.com">About Baidu</a></p><p id="cp">©2015 Baidu <a href="/duty/">使用百度前必读</a> <a href="http://www.miibeian.gov.cn" target="_blank">京ICP证030173号</a> <img src="http://gimg.baidu.com/img/gs.gif"></p></div><map name="mp"><area shape="rect" coords="40,25,230,95" href="http://hi.baidu.com/baidu/" target="_blank" title="点此进入 百度的空间" ></map></body>
<script>var w=window,d=document,n=navigator,k=d.f.wd,a=d.getElementById("nv").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.opera,sh=d.getElementById("sh");if(isIE&&sh&&!sh.isHomePage("http://www.baidu.com/")){sh.style.display="inline"}for(var i=0;i<a.length;i++){a[i].onclick=function(){if(k.value.length>0){var C=this,A=C.href,B=encodeURIComponent(k.value);if(A.indexOf("q=")!=-1){C.href=A.replace(/q=[^&$]*/,"q="+B)}else{this.href+="?q="+B}}}}(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(RegExp.$1)}})();if(n.cookieEnabled&&!/sug?=0/.test(d.cookie)){d.write('<script src=http://www.baidu.com/js/bdsug.js?v=1.0.3.0><\/script>')}function addEV(C,B,A){if(w.attachEvent){C.attachEvent("on"+B,A)}else{if(w.addEventListener){C.addEventListener(B,A,false)}}}function G(A){return d.getElementById(A)}function ns_c(E){var F=encodeURIComponent(window.document.location.href),D="",A="",B="",C=window["BD_PS_C"+(new Date()).getTime()]=new Image();for(v in E){A=E[v];D+=v+"="+A+"&"}B="&mu="+F;C.src="http://nsclick.baidu.com/v.gif?pid=201&pj=www&"+D+"path="+F+"&t="+new Date().getTime();return true}var bdimeHW={hasF:1};var imeTar="kw";var ime_t1=(new Date()).getTime();(function(){var M=G("mCon"),A=G("mMenu");var B=["输入法","手写","拼音"],O=["cl","hw","py"],D=["","http://www.baidu.com/hw/hwInput_1.1.js","http://www.baidu.com/olime/bdime.js"],N=[0,0,0];var L=n.cookieEnabled;if(L&&/\bbdime=(\d)/.test(d.cookie)){H(O[RegExp.$1],false)}var K=A.getElementsByTagName("a");for(var I=0;I<K.length;I++){K[I].onclick=F}if(isIE){var E=[];var P=M.getElementsByTagName("*");for(var I=0;I<P.length;I++){E.push(P[I])}E.push(M);var P=A.getElementsByTagName("*");for(var I=0;I<P.length;I++){E.push(P[I])}E.push(A);for(var I=0;I<E.length;I++){E[I].setAttribute("unselectable","on")}}function F(){ime_t1=(new Date()).getTime();var R=this.name.split("_")[1];try{if(w.bdime){bdime.control.closeIme()}}catch(Q){}H(R,true);return false}function H(V,Q){var T=0;if(V==O[1]){T=1;M.innerHTML='<span id="imeS" class="hw">'+B[1]+"</span>";if(isIE){G("imeS").setAttribute("unselectable","on")}function S(){if(!N[1]){if(d.selection&&d.activeElement.id&&d.activeElement.id=="kw"){bdimeHW.hasF=1}bdimeHW.input=imeTar;bdimeHW.submit="su";J(D[1]);setTimeout(function(){if(typeof bdsug!="undefined"){bdsug.sug.initial()}},1000);N[1]=1}else{bdimeHW.reload(Q)}}if(Q){S()}else{addEV(G("imeS"),"click",S)}}else{if(V==O[2]){T=2;M.innerHTML="<span>"+B[2]+"</span>";if(!N[2]){J(D[2]);N[2]=1}else{try{if(w.bdime){bdime.control.openIme()}}catch(U){}}}else{M.innerHTML="<span>"+B[0]+"</span>"}}if(Q&&L){var R=new Date();R.setTime(R.getTime()+365*24*3600*1000);d.cookie="bdime="+T+";domain=baidu.com;path=/;expires="+R.toGMTString()}}function J(Q){if(Q){var R=d.createElement("script");R.src=Q;d.getElementsByTagName("head")[0].appendChild(R)}}function C(R){var R=R||window.event;var Q=R.target||R.srcElement;A.style.display=Q.id=="mCon"&&A.style.display!="block"?"block":"none"}addEV(d,"click",C)})();addEV(w,"load",function(){k.focus()});w.onunload=function(){};;</script>
<script type="text/javascript" src="http://www.baidu.com/cache/hps/js/hps-1.1.js"></script>
</html>