GVKun编程网logo

异常运行Boost Asio SSL示例(异常运行方式)

18

以上就是给各位分享异常运行BoostAsioSSL示例,其中也会对异常运行方式进行解释,同时本文还将给你拓展boostasio、BoostasioIO多路复用、boost------asio库的使用1

以上就是给各位分享异常运行Boost Asio SSL示例,其中也会对异常运行方式进行解释,同时本文还将给你拓展boost asio、Boost asio IO多路复用、boost------asio 库的使用 1 (Boost 程序库完全开发指南) 读书笔记、boost------asio库的使用2(Boost程序库完全开发指南)读书笔记等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

异常运行Boost Asio SSL示例(异常运行方式)

异常运行Boost Asio SSL示例(异常运行方式)

我试图从boost :: asio运行SSL示例,并且在运行它们时遇到“无效参数”异常。我在Linux x86_64上。

http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/ssl/client.cpp

http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/ssl/server.cpp

编译:

g++ server.cpp -o server -lboost_system -lsslg++ client.cpp -o client -lboost_system -lssl

运行像:

$ ./server Usage: server <port>$ ./server 10000Exception: Invalid argument$ ./server 1000Exception: Permission denied$ sudo ./server 1000Exception: Invalid argument

不知道是什么问题:(任何帮助将不胜感激。

谢谢!

答案1

小编典典

好的,对于将来发现此问题的任何人,您都需要创建证书并进行适当的签名。这是Linux的命令:

//生成私钥

openssl genrsa -des3 -out server.key 1024

//生成证书签名请求

openssl req -new -key server.key -out server.csr

//用私钥签名证书

openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt

//删除密码要求(例如,需要)

cp server.key server.key.secureopenssl rsa -in server.key.secure -out server.key

//生成dhparam文件

openssl dhparam -out dh512.pem 512

完成此操作后,您需要更改server.cpp和client.cpp中的文件名。

server.cpp

context_.use_certificate_chain_file("server.crt"); context_.use_private_key_file("server.key", boost::asio::ssl::context::pem);context_.use_tmp_dh_file("dh512.pem");

client.cpp

ctx.load_verify_file("server.crt");

然后,它应该一切正常!

boost asio

boost asio

在用 async_read 接收客户端消息的时候,用 tcpdum 可以看到 ACK 显示服务端全部接收,为何打印的时候发现丢掉了,比如说一条消息重复连续发 5 次只能收到一次,async_read_some 却不会,请告诉解答

Boost asio IO多路复用

Boost asio IO多路复用

设计思路
多个链路对应一个IO 多个是几个
所有串口用一个IO
TCP每10个用一个IO

总IO个数-CPU核数。
最优方案:
多个task/thread对应一个IO,IO总个数是=cpu core数。


https://www.cnblogs.com/fnlingnzb-learner/p/10402276.html
https://www.cnblogs.com/qbin/p/10860606.html
https://www.cnblogs.com/shirley18/p/9767622.html
https://www.zhihu.com/question/272025783
https://www.cnblogs.com/fnlingnzb-learner/p/10402232.html
https://blog.csdn.net/ybxuwei/article/details/53352603
 

 

多串口绑定单IO,多线程处理异步read伪代码

IoThreadPool

    io_service io    //io共享

    work

    threads//多线程

    start(threads.join)

 

serialport

    strand m_strand;

    std::array<char, 8192> m_readBuffer;

open(

、、init io

init serialportparam

open

doWrite(str,len)

doRead(){

        //异步读取绑定

       async_read_some(m_readBuffer,size, m_strand[this,self](error ec, int nlen){

                if(!ec){

                string strRead = m_readBuffer[nlen];                  

                processReadstr();

                doRead();//循环 一定要循环,XXX很多例子都没说清楚为什么要循环

                }

                else{

                        excption

                }

})

}

 

 

 

tcp类似,加上心跳检测连接状态,

reconnect

 

boost------asio 库的使用 1 (Boost 程序库完全开发指南) 读书笔记

boost------asio 库的使用 1 (Boost 程序库完全开发指南) 读书笔记

asio 库基于操作系统提供的异步机制,采用前摄器设计模式 (Proactor) 实现了可移植的异步 (或者同步) IO 操作,而且并不要求多线程和锁定,有效地避免了多线程编程带来的诸多有害副作用。

 

目前 asio 主要关注于网络通信方面,使用大量的类和函数封装了 socket API,支持 TCP、TCMP、UDP 等网络通信协议。但 asio 的异步操作并不局限于网络编程,它还支持串口读写、定时器、SSL 等功能,而且 asio 是一个很好的富有弹性的框架,可以扩展到其他有异步操作需要的领域

 

 

概述

asio 库基于前摄器模式封装了操作系统的 select、poll/epoll、kqueue、overlapped I/O 等机制,实现了异步 IO 模型。它的核心类 io_service,相当于前摄器模式中的 Proactor 角色,asio 的任何操作都需要有 io_service 的参与。

 

在同步模式下,程序发起一个 IO 操作,向 io_service 提交请求,io_service 把操作转交给操作系统,同步地等待。当 IO 操作完成时,操作系统通知 io_service,然后 io_service 再把结果发回给程序,完成整个同步流程。这个处理流程与多线程的 join () 等待方式很相似。

 

在异步模式下,程序除了要发起的 IO 操作,还要定义一个用于回调的完成处理函数。io_service 同样把 IO 操作转交给操作系统执行,但它不同步等待,而是立即返回。调用 io_service 的 run () 成员函数可以等待异步操作完成,当异步操作完成时 io_service 从操作系统获取执行结果,调用完成处理函数。

 

asio 不直接使用操作系统提供的线程,而是定义了一个自己的线程概念:strand,它保证在多线程的环境中代码可以正确地执行,而无需使用互斥量。io_service::strand::wrap () 函数可以包装一个函数在 strand 中执行。

 

asio 库使用 system 库的 error_code 和 system_error 来表示程序运行的错误。

 

定时器

 

定时器是 asio 库里最简单的一个 IO 模型示范,提供等待时间终止的功能,通过它我们可以快速熟悉 asio 的基本使用方法:

同步定时器

 

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. #include "stdafx.h"  
  2. #include "boost/asio.hpp"  
  3. #include "boost/date_time/posix_time/posix_time.hpp"  
  4. #include "iostream"  
  5. using namespace std;  
  6.   
  7.   
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.     boost::asio::io_service ios;    // 所以的 asio 程序必须要有一个 io_service 对象  
  11.   
  12.     // 定时器 io_service 作为构造函数参数,两秒钟之后定时器终止  
  13.     boost::asio::deadline_timer t(ios, boost::posix_time::seconds(2));  
  14.   
  15.     cout << t.expires_at() << endl; // 查看终止的绝对事件  
  16.   
  17.     t.wait();                       // 调用 wait 同步等待  
  18.     cout << "hello asio" << endl;  
  19.   
  20.     return 0;  
  21. }  

 

 

可以把它与 thread 库的 sleep () 函数对比研究一下,两者都是等待,但内部机制完成不同:thread 库的 sleep () 使用了互斥量和条件变量,在线程中等待,而 asio 则是调用了操作系统的异步机制,如 select、epoll 等完成的。

 

 

异步定时器

下面的是异步定时器,代码大致与同步定时器相等,增加了回调函数,并使用 io_service.run () 和定时器的 async_wait () 方法

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. #include "stdafx.h"  
  2. #include "boost/asio.hpp"  
  3. #include "boost/date_time/posix_time/posix_time.hpp"  
  4. #include "iostream"  
  5. using namespace std;  
  6.   
  7.   
  8. void Print(const boost::system::error_code& error)  
  9. {  
  10.     cout << "hello asio" << endl;  
  11. }  
  12.   
  13.   
  14. int _tmain(int argc, _TCHAR* argv[])  
  15. {  
  16.     boost::asio::io_service ios;    // 所以的 asio 程序必须要有一个 io_service 对象  
  17.   
  18.     // 定时器 io_service 作为构造函数参数,两秒钟之后定时器终止  
  19.     boost::asio::deadline_timer t(ios, boost::posix_time::seconds(2));  
  20.   
  21.     t.async_wait(Print);                        // 调用 wait 异步等待  
  22.   
  23.     cout << "it show before t expired." << endl;  
  24.   
  25.     ios.run();  
  26.   
  27.     return 0;  
  28. }  

代码的前两行与同步定时器相同,这是所有 asio 程序基本的部分。重要的是异步等待 async_wait (),它通知 io_service 异步地执行 io 操作,并且注册了回调函数,用于在 io 操作完成时由事件多路分离器分派返回值 (error_code) 调用

 

最后必须调用 io_service 的 run () 成员函数,它启动前摄器的事件处理循环,阻塞等待所有的操作完成并分派事件。如果不调用 run () 那么虽然操作被异步执行了,但没有一个等待它完成的机制,回调函数将得不到执行机会。

 

 

异步定时器使用 bind

异步定时器中由于引入了回调函数,因此产生了很多的变化,可以增加回调函数的参数,使它能够做更多的事情。但 async_wait () 接受的回调函数类型是固定的,必须使用 bind 库来绑定参数以适配它的接口

   下面实现一个可以定时执行任意函数的定时器 AsynTimer (asyctimer),它持有一个 asio 定时器对象和一个计数器,还有一个 function 对象来保存回调函数

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. #include "stdafx.h"  
  2. #include "boost/asio.hpp"  
  3. #include "boost/date_time/posix_time/posix_time.hpp"  
  4. #include "boost/bind.hpp"  
  5. #include "boost/function.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. class AsynTimer  
  11. {  
  12. public:  
  13.     template<typename F>                              // 模板类型,可以接受任意可调用物  
  14.     AsynTimer(boost::asio::io_service& ios, int x, F func)  
  15.         :f(func), count_max(x), count(0),               // 初始化回调函数和计数器  
  16.         t(ios, boost::posix_time::millisec(500))        // 启动计时器  
  17.     {  
  18.         t.async_wait(boost::bind(&AsynTimer::CallBack,  // 异步等待计时器  
  19.             this, boost::asio::placeholders::error));   // 注册回调函数  
  20.     }  
  21.   
  22.     void CallBack(const boost::system::error_code& error)  
  23.     {  
  24.         if (count >= count_max)   // 如果计数器达到上限则返回  
  25.         {  
  26.             return;  
  27.         }  
  28.         ++count;  
  29.         f();                     // 调用 function 对象  
  30.   
  31.         // 设置定时器的终止时间为 0.5 秒之后  
  32.         t.expires_at(t.expires_at() + boost::posix_time::microsec(500));  
  33.         // 再次启动定时器,异步等待  
  34.         t.async_wait(boost::bind(&AsynTimer::CallBack, this, boost::asio::placeholders::error));  
  35.     }  
  36.   
  37. private:  
  38.     int count;  
  39.     int count_max;  
  40.     boost::function<void()> f;        // function 对象,持有无参无返回值的可调用物  
  41.     boost::asio::deadline_timer t;  // asio 定时器对象  
  42. };  
  43.   
  44. // 第一个回调函数  
  45. void print1()  
  46. {  
  47.     cout << "hello asio" << endl;  
  48. }  
  49.   
  50. // 第二个回调函数  
  51. void print2()  
  52. {  
  53.     cout << "hello boost" << endl;  
  54. }  
  55.   
  56.   
  57. int _tmain(int argc, _TCHAR* argv[])  
  58. {  
  59.     boost::asio::io_service ios;  
  60.   
  61.     AsynTimer t1(ios, 10, print1); // 启动第一个定时器  
  62.     AsynTimer t2(ios, 10, print2); // 启动第二个定时器  
  63.   
  64.     ios.run();  // io_service 等待异步调用结束  
  65.   
  66.     return 0;  
  67. }  

 

注意在 async_wait () 中 bind 的用法,CallBack 是 AsynTimer 的一个成员函数,因此需要绑定 this 指针,同时还使用了 asio 下子名字空间 placeholders 下的一个占位符 error,他的作业类似于 bind 库的占位符_1、_2,用于传递 error_code 值。

 

接下来是 AsynTimer 的主要功能函数 CallBack,它符合 async_wait () 对回调函数的要求,有一个 error_code 参数,当定时器终止时它将被调用执行

 

CallBack 函数内部累加器,如果计数器未达到上限则调用 function 对象 f,然后重新设置定时器的终止时间,再次异步等待被调用,从而达到反复执行的目的

boost------asio库的使用2(Boost程序库完全开发指南)读书笔记

boost------asio库的使用2(Boost程序库完全开发指南)读书笔记

网络通信

 

asio库支持TCP、UDP、ICMP通信协议,它在名字空间boost::asio::ip里提供了大量的网络通信方面的函数和类,很好地封装了原始的Berkeley Socket Api,展现给asio用户一个方便易用且健壮的网络通信库。

 

ip::tcp类是asio网络通信(TCP)部分主要的类,但它本身并没有太多的功能,而是定义了数个用于TCP通信的typedef类型,用来协作完成网络通信。这些typedef包括端点类endpoint、套接字类socket、流类iostream,以及接收器acceptor、解析器resolver等等。从某种程度上来看,ip::tcp类更像是一个名字空间。

 

1、IP地址和端点

IP地址独立于TCP、UDP等通信协议,asio库使用类ip::address来表示IP地址,可以同时支持ipv4和ipv6两种地址。

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. #include "stdafx.h"  
  2. #include "boost/asio.hpp"  
  3. #include "boost/date_time/posix_time/posix_time.hpp"  
  4. #include "boost/bind.hpp"  
  5. #include "boost/function.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     boost::asio::ip::address addr;          // 声明一个ip地址对象  
  13.     addr = addr.from_string("127.0.0.1");   // 从字符串产生IP地址  
  14.     assert(addr.is_v4());                   // ipv4的地址  
  15.     cout << addr.to_string() << endl;  
  16.   
  17.     addr = addr.from_string("2000:0000:0000:0000:0001:2345:6789:abcd");  
  18.     assert(addr.is_v6());  
  19.     cout << addr.to_string() << endl;  
  20.   
  21.     return 0;  
  22. }  

 

 

有了IP地址,再加上通信用的端口号就构成了一个socket端点,在asio库中用ip::tcp::endpoint类来表示。它的主要用法就是通过构造函数创建一个可用于socket通信的端点对象,端点的地址和端口号可以用address()和port()获得:

 

 

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. #include "stdafx.h"  
  2. #include "boost/asio.hpp"  
  3. #include "boost/date_time/posix_time/posix_time.hpp"  
  4. #include "boost/bind.hpp"  
  5. #include "boost/function.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     boost::asio::ip::address addr;          // 声明一个ip地址对象  
  13.     addr = addr.from_string("127.0.0.1");   // 从字符串产生IP地址  
  14.   
  15.     boost::asio::ip::tcp::endpoint ep(addr, 6688);  
  16.   
  17.     assert(ep.address() == addr);  
  18.     assert(ep.port() == 6688);  
  19.   
  20.     return 0;  
  21. }  


 

 

 

2、同步socket处理

 

ip::tcp的内部类型socket、acceptor和resolver是asio库TCP通信中最核心的一组类,它们封装了socket的连接、断开和数据收发功能,使用它们可以很容易地编写出socket程序。

 

socket类是TCP通信的基本类,调用成员函数connect()可以连接到一个指定的通信端点,连接成功后用local_endpoint()和remote_endpoint()获得连接两端的端点信息,用read_some()和write_some()阻塞读写数据,当操作完成后使用close()函数关闭socket。如果不关闭socket,那么在socket对象析构时也会自动调用close()关闭。

 

acceptor类对应socketAPI的accept()函数功能,它用于服务器端,在指定的端口号接受连接,必须配合socket类才能完成通信。

 

resolver类对应socketAPI的getaddrinfo()系列函数,用于客户端解析网址获得可用的IP地址,解析得到的IP地址可以使用socket对象连接。

 

下面是一个使用socket类和acceptor类来实现一对同步通信的服务器和客户端程序:

服务器端(它使用一个acceptor对象在6688端口接受连接,当有连接时使用一个socket对象发送一个字符串):

 

server.cpp:

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. // server.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "boost/asio.hpp"  
  6. #include "boost/date_time/posix_time/posix_time.hpp"  
  7. #include "boost/bind.hpp"  
  8. #include "boost/function.hpp"  
  9. #include "iostream"  
  10. using namespace std;  
  11.   
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     try  
  16.     {  
  17.         cout << "server start" << endl;  
  18.         boost::asio::io_service ios;  
  19.   
  20.         boost::asio::ip::tcp::acceptor acceptor(ios,   
  21.             boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 6688));  
  22.   
  23.         cout << acceptor.local_endpoint().address() << endl;  
  24.   
  25.         while (true)  
  26.         {  
  27.             boost::asio::ip::tcp::socket sock(ios);  
  28.             acceptor.accept(sock);  
  29.   
  30.             cout << "client : ";  
  31.             cout << sock.remote_endpoint().address() << endl;  
  32.   
  33.             sock.write_some(boost::asio::buffer("hello asio"));  
  34.         }  
  35.     }  
  36.   
  37.     catch (std::exception& e)  
  38.     {  
  39.         cout << e.what() << endl;  
  40.     }  
  41.   
  42.     return 0;  
  43. }  

服务器端程序里要注意的是自由函数buffer(),他可以包装很多种类的容器成为asio组件可用的缓冲区类型。通常不能直接把数组、vercor等容器用作asio的读写参数,必须使用buffer()函数包装

 

 

client:

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. // client.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "boost/asio.hpp"  
  6. #include "boost/date_time/posix_time/posix_time.hpp"  
  7. #include "boost/bind.hpp"  
  8. #include "boost/function.hpp"  
  9. #include "iostream"  
  10. using namespace std;  
  11. #include "vector"  
  12.   
  13.   
  14. class AsynTimer  
  15. {  
  16. public:  
  17.     template<typename F>                              // 模板类型,可以接受任意可调用物  
  18.     AsynTimer(boost::asio::io_service& ios, int x, F func)  
  19.         :f(func), count_max(x), count(0),               // 初始化回调函数和计数器  
  20.         t(ios, boost::posix_time::millisec(500))        // 启动计时器  
  21.     {  
  22.         t.async_wait(boost::bind(&AsynTimer::CallBack,  // 异步等待计时器  
  23.             this, boost::asio::placeholders::error));   // 注册回调函数  
  24.     }  
  25.   
  26.     void CallBack(const boost::system::error_code& error)  
  27.     {  
  28.         if (count >= count_max)   // 如果计数器达到上限则返回  
  29.         {  
  30.             return;  
  31.         }  
  32.         ++count;  
  33.         f();                     // 调用function对象  
  34.   
  35.         // 设置定时器的终止时间为0.5秒之后  
  36.         t.expires_at(t.expires_at() + boost::posix_time::microsec(500));  
  37.         // 再次启动定时器,异步等待  
  38.         t.async_wait(boost::bind(&AsynTimer::CallBack, this, boost::asio::placeholders::error));  
  39.     }  
  40.   
  41. private:  
  42.     int count;  
  43.     int count_max;  
  44.     boost::function<void()> f;        // function对象,持有无参无返回值的可调用物  
  45.     boost::asio::deadline_timer t;  // asio定时器对象  
  46. };  
  47.   
  48.   
  49. void client(boost::asio::io_service& ios)  
  50. {  
  51.     try  
  52.     {  
  53.         cout << "client start." << endl;  
  54.   
  55.         boost::asio::ip::tcp::socket sock(ios);  
  56.         boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 6688);  
  57.   
  58.         sock.connect(ep);  
  59.   
  60.         vector<char> str(100, 0);  
  61.         sock.read_some(boost::asio::buffer(str));  
  62.   
  63.         cout << "recive from" << sock.remote_endpoint().address();  
  64.         cout << &str[0] << endl;  
  65.   
  66.     }  
  67.     catch (std::exception& e)  
  68.     {  
  69.         cout << e.what() << endl;  
  70.     }  
  71. }  
  72.   
  73.   
  74. int _tmain(int argc, _TCHAR* argv[])  
  75. {  
  76.     boost::asio::io_service ios;  
  77.     AsynTimer at(ios, 50000, boost::bind(client, boost::ref(ios)));  
  78.     ios.run();  
  79.   
  80.     return 0;  
  81. }  

 

3、异步socket处理

我们把刚才的同步socket程序改为异步调用方式。异步程序的处理流程与同步程序基本相同,只需要把原有的同步调用函数都换成前缀是async_的异步调用函数,并增加回调函数,在回调函数中再启动一个异步调用

 

服务器端:

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. // server.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "boost/asio.hpp"  
  6. #include "boost/date_time/posix_time/posix_time.hpp"  
  7. #include "boost/bind.hpp"  
  8. #include "boost/function.hpp"  
  9. #include "iostream"  
  10. using namespace std;  
  11.   
  12.   
  13. class Server  
  14. {  
  15. private:  
  16.     boost::asio::io_service& ios;  
  17.     boost::asio::ip::tcp::acceptor acceptor;  
  18.     typedef boost::shared_ptr<boost::asio::ip::tcp::socket> sock_pt;  
  19.   
  20. public:  
  21.     Server(boost::asio::io_service& io) : ios(io),  
  22.         acceptor(ios, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 6688))  
  23.     {  
  24.         Start();  
  25.     }  
  26.     ~Server()  
  27.     {  
  28.   
  29.     }  
  30.   
  31.     void Start()  
  32.     {  
  33.         sock_pt sock(new boost::asio::ip::tcp::socket(ios));    // 智能指针  
  34.   
  35.         // 异步侦听服务  
  36.         acceptor.async_accept(*sock, boost::bind(&Server::acceptor_handle,   
  37.                                                  this, boost::asio::placeholders::error, sock));  
  38.     }  
  39.   
  40.     void acceptor_handle(const boost::system::error_code& error, sock_pt sock)  
  41.     {  
  42.         if (error)  
  43.         {  
  44.             return;  
  45.         }  
  46.         cout << "client : ";  
  47.   
  48.         // 输出连接的客户端信息  
  49.         cout << sock->remote_endpoint().address() << endl;  
  50.   
  51.         //   
  52.         sock->async_write_some( boost::asio::buffer("hello asio"),   
  53.                                 boost::bind(&Server::write_handle,  
  54.                                 this, boost::asio::placeholders::error));  
  55.   
  56.         Start(); // 再次启动异步接受连接  
  57.     }  
  58.   
  59.     void write_handle(const boost::system::error_code& error)  
  60.     {  
  61.         cout << "send message is complate" << endl;  
  62.     }  
  63.   
  64. };  
  65.   
  66.   
  67. int _tmain(int argc, _TCHAR* argv[])  
  68. {  
  69.     try  
  70.     {  
  71.         cout << "server start." << endl;  
  72.   
  73.         boost::asio::io_service ios;  
  74.   
  75.         Server serv(ios);  
  76.   
  77.         ios.run();  
  78.     }  
  79.     catch (std::exception& e)  
  80.     {  
  81.         cout << e.what() << endl;  
  82.     }  
  83.   
  84.     return 0;  
  85. }  

 

首先检查asio传递的error_code,保证没有错误发生。然后调用socket对象的async_write_some()异步发送数据。同样,我们必须再为这个异步调用编写回调函数write_handler()。当发送完数据后不要忘记调用Start()再次启动服务器接受链接,否则当完成数据发送后io_service将因为没有时间处理而结束运行。

 

发送数据的回调函数write_handler()很简单,因为不需要做更多的工作,可以直接实现一个空函数,在这里简单地输出一条信息,表示异步发送数据完成

 

 

客户端:

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. // client.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "boost/asio.hpp"  
  6. #include "boost/date_time/posix_time/posix_time.hpp"  
  7. #include "boost/bind.hpp"  
  8. #include "boost/function.hpp"  
  9. #include "iostream"  
  10. using namespace std;  
  11. #include "vector"  
  12.   
  13.   
  14. class Client  
  15. {  
  16. private:  
  17.     boost::asio::io_service& ios;  
  18.     boost::asio::ip::tcp::endpoint ep;  // tcp端点  
  19.     typedef boost::shared_ptr<boost::asio::ip::tcp::socket> sock_pt;  
  20.   
  21. public:  
  22.     Client(boost::asio::io_service& io) : ios(io),  
  23.         ep(boost::asio::ip::address::from_string("127.0.0.1"), 6688)  
  24.     {  
  25.         Start(); // 启动异步连接  
  26.     }  
  27.   
  28.     ~Client()  
  29.     {  
  30.   
  31.     }  
  32.   
  33.     void Start()  
  34.     {  
  35.         sock_pt sock(new boost::asio::ip::tcp::socket(ios));  
  36.         sock->async_connect(ep, boost::bind(&Client::conn_handle, this,  
  37.                                             boost::asio::placeholders::error, sock));  
  38.     }  
  39.   
  40.     void conn_handle(const boost::system::error_code& error, sock_pt sock)  
  41.     {  
  42.         if (error)  
  43.         {  
  44.             return;  
  45.         }  
  46.         cout << "recive from : " << sock->remote_endpoint().address();  
  47.   
  48.         // 建立接收数据的缓冲区  
  49.         boost::shared_ptr<vector<char> > str(new vector<char>(100, 0));  
  50.   
  51.         // 异步读取数据  
  52.         sock->async_read_some(boost::asio::buffer(*str), boost::bind(&Client::read_handle,  
  53.                                                                     this,   
  54.                                                                     boost::asio::placeholders::error,  
  55.                                                                     str));  
  56.         Start(); // 再次启动异步连接  
  57.     }  
  58.   
  59.     void read_handle(const boost::system::error_code& error,   
  60.                      boost::shared_ptr<vector<char> > str)  
  61.     {  
  62.         if (error)  
  63.         {  
  64.             return;  
  65.         }  
  66.         cout << &(*str)[0] << endl;  
  67.     }  
  68. };  
  69.   
  70.   
  71. int _tmain(int argc, _TCHAR* argv[])  
  72. {  
  73.     try  
  74.     {  
  75.         cout << "client start." << endl;  
  76.         boost::asio::io_service ios;  
  77.   
  78.         Client client(ios);  
  79.   
  80.         ios.run();  
  81.     }  
  82.     catch (std::exception& e)  
  83.     {  
  84.         cout << e.what() << endl;  
  85.     }  
  86.   
  87.     return 0;  
  88. }  

 

 

4、查询网络地址

之前关于tcp通信的所有论述都是使用直接的ip地址,但在实际生活中大多数时候,都不大可能知道socket链接另一端的地址,而只有一个域名,这时候我们就需要使用resolver类来通过域名获得可用的ip,它可以实现与ip版本无关的网址解析

 

resolver使用内部类query和iterator共同完成查询ip地址的工作:首先使用网址和服务名创建query对象,然后由resolve()函数生成iterator对象,它代表了查询到的ip端点。之后就可以使用socket对象尝试连接,知道找到一个可用的为止。

[cpp] view plain copy

 print?在CODE上查看代码片派生到我的代码片

  1. #include "stdafx.h"  
  2. #include "boost/asio.hpp"  
  3. #include "boost/date_time/posix_time/posix_time.hpp"  
  4. #include "boost/bind.hpp"  
  5. #include "boost/function.hpp"  
  6. #include "boost/lexical_cast.hpp"  
  7. #include "boost/asio/error.hpp"  
  8. #include "iostream"  
  9. using namespace std;  
  10.   
  11.   
  12. void resolv_connect(boost::asio::ip::tcp::socket& sock, const char* name, int port)  
  13. {  
  14.     boost::asio::ip::tcp::resolver rlv(sock.get_io_service());  
  15.     boost::asio::ip::tcp::resolver::query qry(name, boost::lexical_cast<string>(port));  
  16.   
  17.     boost::asio::ip::tcp::resolver::iterator iter = rlv.resolve(qry);  
  18.     boost::asio::ip::tcp::resolver::iterator end;  
  19.   
  20.     boost::system::error_code ec = boost::asio::error::host_not_found;  
  21.     for (; ec && iter != end; ++iter)  
  22.     {  
  23.         sock.close();  
  24.         sock.connect(*iter, ec);  
  25.     }  
  26.   
  27.     if (ec)  
  28.     {  
  29.         cout << "can''t connect." << endl;  
  30.         throw boost::system::error_code(ec);  
  31.     }  
  32.   
  33.     cout << "connet suceessd." << endl;  
  34. }  
  35.   
  36.   
  37. int _tmain(int argc, _TCHAR* argv[])  
  38. {  
  39.     try  
  40.     {  
  41.         boost::asio::io_service ios;  
  42.         boost::asio::ip::tcp::socket sock(ios);  
  43.   
  44.         resolv_connect(sock, "www.boost.org", 80);  
  45.   
  46.         ios.run();  
  47.     }  
  48.     catch (std::exception& e)  
  49.     {  
  50.         cout << e.what() << endl;  
  51.     }  
  52.       
  53.     return 0;  
  54. }  

 

resolv_connect()函数中使用lexical_cast,这是因为query对象只接受字符串参数,所以我们需要把端口号由整数转换为字符串。

 

当开始resolver的迭代时,需要使用error_code和逾尾迭代器两个条件来控制循环,因为有可能迭代完所有解析到的端点都无法连接,只有当error_code为0才表示连接成功。

 

有了resolv_connect()函数,就可以不受具体ip地址值的限制,以更直观更灵活的域名来连接服务器。

我们今天的关于异常运行Boost Asio SSL示例异常运行方式的分享已经告一段落,感谢您的关注,如果您想了解更多关于boost asio、Boost asio IO多路复用、boost------asio 库的使用 1 (Boost 程序库完全开发指南) 读书笔记、boost------asio库的使用2(Boost程序库完全开发指南)读书笔记的相关信息,请在本站查询。

本文标签: