如何在C++中实现fullstack coroutine

 我来答
好程序员
2016-09-12 · HTML5前端培训/大数据培训/Java
好程序员
好程序员是IT高端课程培训基地,从平凡到卓越,为梦想而拼搏。
向TA提问
展开全部
在这里给你举个例子,你自己好好看看你就知道了
#include <boost/asio.hpp>
  #include <boost/asio/spawn.hpp>
  #include <memory>
  #include <functional>
  #include <iostream>

  class session : public std::enable_shared_from_this < session >
  {
  public:
  explicit session(boost::asio::io_service& io_service)
  : strand_(io_service), socket_(io_service)
  {
  }

  boost::asio::ip::tcp::socket& socket()
  {
  return socket_;
  }

  void go()
  {
  boost::asio::spawn(strand_,
  std::bind(&session::echo,
  shared_from_this(), std::placeholders::_1));
  }

  private:
  void echo(boost::asio::yield_context yield)
  {
  char data[128];
  for (;;)
  {
  std::size_t n = socket_.async_read_some(boost::asio::buffer(data), yield);
  boost::asio::async_write(socket_, boost::asio::buffer(data, n), yield);
  }
  }

  boost::asio::io_service::strand strand_;
  boost::asio::ip::tcp::socket socket_;
  };

  void do_accept(boost::asio::io_service& io_service,
  unsigned short port, boost::asio::yield_context yield)
  {
  boost::asio::ip::tcp::acceptor acceptor(
  io_service,
  boost::asio::ip::tcp::endpoint(
  boost::asio::ip::tcp::v4(), port));

  for (;;)
  {
  boost::system::error_code ec;
  std::shared_ptr<session> new_session(std::make_shared<session>(io_service));
  acceptor.async_accept(new_session->socket(), yield[ec]);
  if (!ec)
  {
  new_session->go();
  }
  }
  }

  int main(int argc, char* argv[])
  {
  try
  {
  boost::asio::io_service io_service;

  boost::asio::spawn(io_service,
  std::bind(do_accept,
  std::ref(io_service), 8888, std::placeholders::_1));

  io_service.run();
  }
  catch (std::exception& e)
  {
  std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
  }
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式