asio入门资料

举报
风吹稻花香 发表于 2021/06/04 23:42:16 2021/06/04
【摘要】   下载地址: https://think-async.com/Asio/ 选择asio独立的版本。   server:这个server 有时会有乱码的问题: // asio_server.cpp : 定义控制台应用程序的入口点。// #include "stdafx.h"#include <asio.hpp> using name...

 

下载地址:

https://think-async.com/Asio/

选择asio独立的版本。

 

server:这个server 有时会有乱码的问题:


  
  1. // asio_server.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <asio.hpp>
  5. using namespace asio;
  6. using asio::ip::tcp;
  7. class session : public std::enable_shared_from_this<session>
  8. {
  9. public:
  10. session(tcp::socket s) : socket_(std::move(s)) {}
  11. void start()
  12. {
  13. async_read();
  14. }
  15. private:
  16. void async_read()
  17. {
  18. auto self(shared_from_this());
  19. socket_.async_read_some(asio::buffer(data_), // 异步读
  20. [this, self](const asio::error_code &ec, size_t bytes_transferred) // 读操作完成时回调该函数
  21. { // 捕获`self`使shared_ptr<session>的引用计数增加1,在该例中避免了async_read()退出时其引用计数变为0
  22. if (!ec) {
  23. printf("rece %d\n", bytes_transferred);
  24. for (int i = 0; i < 5;i++) {
  25. async_write(bytes_transferred); // 读完即写
  26. Sleep(10);
  27. }
  28. }
  29. }
  30. );
  31. }
  32. void async_write(std::size_t length)
  33. {
  34. auto self(shared_from_this());
  35. asio::async_write(socket_, asio::buffer(data_, length), // 异步写
  36. [this, self](const asio::error_code &ec, size_t)
  37. {
  38. if (!ec)
  39. async_read();
  40. }
  41. );
  42. }
  43. tcp::socket socket_; // “会话”基于已经建立的socket连接
  44. std::array<char, 1024> data_;
  45. };
  46. // 服务器类
  47. // 监听客户端连接请求(async_accept)。与某个客户端建立socket连接后,为它创建一个session
  48. class server
  49. {
  50. public:
  51. server(asio::io_service &io_service, short port)
  52. : acceptor_(io_service, tcp::endpoint(tcp::v4(), port)), socket_(io_service)
  53. {
  54. async_accept();
  55. }
  56. private:
  57. void async_accept()
  58. {
  59. acceptor_.async_accept(socket_, std::bind(&server::handle_accept, this, std::placeholders::_1)); // 异步accept。socket连接建立后,调用handle_accept()
  60. }
  61. void handle_accept(const asio::error_code &ec)
  62. {
  63. if (!ec)
  64. {
  65. printf("new conn %s\n", socket_.remote_endpoint().address());
  66. std::shared_ptr<session> session_ptr(new session(std::move(socket_)));
  67. session_ptr->start();
  68. }
  69. async_accept(); // 继续监听客户端连接请求
  70. }
  71. tcp::acceptor acceptor_;
  72. tcp::socket socket_;
  73. };
  74. int main(int argc, char* argv[])
  75. {
  76. asio::io_service io_service;
  77. server s(io_service, 5200);
  78. io_service.run();
  79. return 0;
  80. }

 

client:

 


  
  1. #include "stdafx.h"
  2. #include <array>
  3. #include <functional>
  4. #include <iostream>
  5. #include <memory>
  6. #include <string>
  7. #include "asio.hpp"
  8. //#include "utility.h" // for printing endpoints
  9. using asio::ip::tcp;
  10. // Use async_resolve() or not.
  11. #define RESOLVE_ASYNC 1
  12. // Only resolve IPv4.
  13. #define RESOLVE_IPV4_ONLY 1
  14. // -----------------------------------------------------------------------------
  15. class Client {
  16. public:
  17. Client(asio::io_context& io_context,
  18. const std::string& host, const std::string& port);
  19. private:
  20. #if RESOLVE_ASYNC
  21. void OnResolve(asio::error_code ec,
  22. tcp::resolver::results_type endpoints);
  23. #endif // RESOLVE_ASYNC
  24. void OnConnect(asio::error_code ec, tcp::endpoint endpoint);
  25. void DoWrite();
  26. void OnWrite(asio::error_code ec);
  27. void OnRead(asio::error_code ec, std::size_t length);
  28. tcp::socket socket_;
  29. #if RESOLVE_ASYNC
  30. tcp::resolver resolver_;
  31. #endif
  32. enum { BUF_SIZE = 1024 };
  33. char cin_buf_[BUF_SIZE];
  34. // NOTE: std::vector is better than std::array in practice.
  35. std::array<char, BUF_SIZE> buf_;
  36. };
  37. // -----------------------------------------------------------------------------
  38. Client::Client(asio::io_context& io_context,
  39. const std::string& host, const std::string& port)
  40. #if RESOLVE_ASYNC
  41. : socket_(io_context), resolver_(io_context) {
  42. #else
  43. : socket_(io_context) {
  44. #endif
  45. #if RESOLVE_ASYNC
  46. resolver_.async_resolve(tcp::v4(), host, port,
  47. std::bind(&Client::OnResolve, this,
  48. std::placeholders::_1,
  49. std::placeholders::_2));
  50. #else
  51. // If you don't specify tcp::v4() as the first parameter (protocol) of
  52. // resolve(), the result will have two endpoints, one for v6, one for
  53. // v4. The first v6 endpoint will fail to connect.
  54. tcp::resolver resolver(io_context);
  55. #if RESOLVE_IPV4_ONLY
  56. auto endpoints = resolver.resolve(tcp::v4(), host, port);
  57. // 127.0.0.1:2017, v4
  58. #else
  59. auto endpoints = resolver.resolve(host, port);
  60. // [::1]:2017, v6
  61. // 127.0.0.1:2017, v4
  62. #endif // RESOLVE_IPV4_ONLY
  63. utility::PrintEndpoints(std::cout, endpoints);
  64. // ConnectHandler: void(asio::error_code, tcp::endpoint)
  65. asio::async_connect(socket_, endpoints,
  66. std::bind(&Client::OnConnect, this,
  67. std::placeholders::_1,
  68. std::placeholders::_2));
  69. #endif // RESOLVE_ASYNC
  70. }
  71. #if RESOLVE_ASYNC
  72. void Client::OnResolve(asio::error_code ec,
  73. tcp::resolver::results_type endpoints) {
  74. if (ec) {
  75. std::cerr << "Resolve: " << ec.message() << std::endl;
  76. }
  77. else {
  78. // ConnectHandler: void(asio::error_code, tcp::endpoint)
  79. asio::async_connect(socket_, endpoints,
  80. std::bind(&Client::OnConnect, this,
  81. std::placeholders::_1,
  82. std::placeholders::_2));
  83. }
  84. }
  85. #endif // RESOLVE_ASYNC
  86. void Client::OnConnect(asio::error_code ec, tcp::endpoint endpoint) {
  87. if (ec) {
  88. std::cout << "Connect failed: " << ec.message() << std::endl;
  89. socket_.close();
  90. }
  91. else {
  92. DoWrite();
  93. }
  94. }
  95. void Client::DoWrite() {
  96. std::size_t len = 0;
  97. do {
  98. std::cout << "Enter message: ";
  99. std::cin.getline(cin_buf_, BUF_SIZE);
  100. len = strlen(cin_buf_);
  101. } while (len == 0);
  102. // TODO: Second parameter
  103. // WriteHandler: void (asio::error_code, std::size_t)
  104. asio::async_write(socket_,
  105. asio::buffer(cin_buf_, len),
  106. std::bind(&Client::OnWrite, this,
  107. std::placeholders::_1));
  108. }
  109. void Client::OnWrite(asio::error_code ec) {
  110. if (!ec) {
  111. std::cout << "Reply is: ";
  112. socket_.async_read_some(asio::buffer(buf_),
  113. std::bind(&Client::OnRead, this,
  114. std::placeholders::_1,
  115. std::placeholders::_2));
  116. }
  117. }
  118. void Client::OnRead(asio::error_code ec, std::size_t length) {
  119. if (!ec) {
  120. std::cout.write(buf_.data(), length);
  121. std::cout << std::endl;
  122. }
  123. }
  124. // -----------------------------------------------------------------------------
  125. int main(int argc, char* argv[]) {
  126. std::string host = "127.0.0.1";
  127. std::string port = "5200";
  128. asio::io_context io_context;
  129. Client client(io_context, host, port);
  130. io_context.run();
  131. while (true)
  132. {
  133. }
  134. system("pause");
  135. return 0;
  136. }

 


  
  1. #include <iostream>
  2. #include <boost/shared_ptr.hpp>
  3. #include <boost/asio.hpp>
  4. #include <boost/asio/placeholders.hpp>
  5. #include <boost/system/error_code.hpp>
  6. #include <boost/bind/bind.hpp>
  7. #include "stdafx.h"
  8. using namespace boost::asio;
  9. using namespace std;
  10. typedef boost::shared_ptr<ip::tcp::socket> sock_ptr;
  11. typedef vector<char> buffer_type;
  12. class client
  13. {
  14. private:
  15. io_service m_io;
  16. buffer_type m_buf;
  17. ip::tcp::endpoint m_ep;
  18. public:
  19. client(): m_buf(100, 0), m_ep(ip::address::from_string("127.0.0.1"), 6688)
  20. { start(); }
  21. void run()
  22. { m_io.run();}
  23. void start()
  24. {
  25. sock_ptr sock(new ip::tcp::socket(m_io));
  26. sock->async_connect(m_ep, boost::bind(&client::conn_handler, this, boost::asio::placeholders::error, sock));
  27. }
  28. void conn_handler(const boost::system::error_code&ec, ip::tcp::socket sock)
  29. {
  30. if (ec)
  31. {return;}
  32. cout<<"Receive from "<<sock->remote_endpoint().address()<<": "<<endl;
  33. sock->async_read_some(buffer(m_buf), boost::bind(&client::read_handler, this, boost::asio::placeholders::error, sock));
  34. }
  35. void read_handler(const boost::system::error_code&ec, ip::tcp::socket sock)
  36. {
  37. if (ec)
  38. {return;}
  39. sock->async_read_some(buffer(m_buf), boost::bind(&client::read_handler, this, boost::asio::placeholders::error, sock));
  40. cout<<&m_buf[0]<<endl;
  41. }
  42. };
  43. int main()
  44. {
  45. try
  46. {
  47. cout<<"Client start."<<endl;
  48. client cli;
  49. cli.run();
  50. }
  51. catch (std::exception &e)
  52. {
  53. cout<<e.what()<<endl;
  54. }
  55. return 0;
  56. }

 

 

// asio_client.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>

#include <iostream>

#include <asio.hpp>


using namespace asio;
using namespace std;

typedef shared_ptr<ip::tcp::socket> sock_ptr;
typedef vector<char> buffer_type;

class client
{

private:
    io_service m_io;
    buffer_type m_buf;
    ip::tcp::endpoint m_ep;
public:
    client() : m_buf(100, 0), m_ep(ip::address::from_string("127.0.0.1"), 8888)
    {
        start();
    }

    void run()
    {
        m_io.run();
    }

    void start()
    {
        sock_ptr sock(new ip::tcp::socket(m_io));
        sock->async_connect(m_ep, bind(&client::conn_handler, this, std::placeholders::_1, sock));
    }

    void conn_handler(const asio::error_code&ec, ip::tcp::socket sock)
    {
        if (ec)
        {
            return;
        }
        cout << "Receive from " << sock.remote_endpoint().address() << ": " << endl;

        //sock.async_read_some(asio::buffer(buffer_),
        sock.async_read_some(buffer(m_buf), bind(&client::read_handler, this, std::placeholders::_1, sock));
    }

    void read_handler(const asio::error_code&ec, ip::tcp::socket sock)
    {
        if (ec)
        {
            return;
        }
        sock.async_read_some(buffer(m_buf), bind(&client::read_handler, this, std::placeholders::_1, sock));
        cout << &m_buf[0] << endl;
    }
};

int main()
{
    try
    {
        cout << "Client start." << endl;
        client cli;
        cli.run();
    }
    catch (std::exception &e)
    {
        cout << e.what() << endl;
    }
    return 0;
}
 

文章来源: blog.csdn.net,作者:网奇,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/jacke121/article/details/89417051

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。