简体   繁体   English

C ++:BOOST_ASIO服务器答复不符合预期吗?

[英]c++: BOOST_ASIO Server reply isn't as expected?

Basically I have a client where I send a string of 10 bytes hellohello to a server and within the server I expect the reply to be 0123456789 back to the client but instead I get hellohello again? 基本上,我有一个客户端,我在其中向服务器发送10字节的字符串hellohello ,并且在服务器内,我希望返回0123456789回复给客户端,但是我又得到了hellohello I changed the char data_ to char data_out on line 58 in the tcp_server.cpp because I thought that was the place to send packet data out? 我改变了char data_char data_out上的tcp_server.cpp 58行,因为我认为这是发送数据包出去的地方? I'm pretty sure that gets called but for some reason things aren't working like I thought. 我很确定会打电话给我,但是由于某些原因,事情并没有按照我的想法工作。

This is the server output, 这是服务器的输出,

handle read: bytes_transferred10
10
handle write:
0123456789
handle read: bytes_transferred0

I also wonder why did handle read: bytes_transferred0 get called again? 我也想知道为什么handle read: bytes_transferred0再次被调用?

This is the client output, 这是客户端输出,

Enter message: hellohello
Reply is: hellohello

Process returned 0 (0x0)   execution time : 6.484 s
Press any key to continue.

This is the tcp_server.cpp 这是tcp_server.cpp

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

class session
{
public:
  session(boost::asio::io_service& io_service)
    : socket_(io_service)
  {
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
          socket_.async_read_some(boost::asio::buffer(data_, max_length),
          boost::bind(&session::handle_read, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }
void read_handler(const boost::system::error_code& ec, std::size_t bytes_transferred);


private:
  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
      std::cout<<"handle read: bytes_transferred"<<bytes_transferred<<std::endl;
    if (!error)
    {
          read_handler(error, bytes_transferred);
          boost::asio::async_write(socket_,
          boost::asio::buffer(data_, bytes_transferred),
          boost::bind(&session::handle_write, this,
          boost::asio::placeholders::error));
    }
    else
    {
      delete this;
    }
  }

  void handle_write(const boost::system::error_code& error)
  {
      std::cout<<"handle write: "<<std::endl;
      data_out = {'0','1','2','3','4','5','6','7','8','9'};
    if (!error)
    {
            std::cout<<data_out<<std::endl;

            socket_.async_read_some(boost::asio::buffer(data_out, max_length),
            boost::bind(&session::handle_read, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }
    else
    {
      delete this;
    }
  }

  tcp::socket socket_;
  enum { max_length = 1024 };
  char data_[max_length];
  char data_out[max_length];
};
void session::read_handler(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
      std::cout<<bytes_transferred<<std::endl;
}

class server
{
public:
  server(boost::asio::io_service& io_service, short port)
    : io_service_(io_service),
      acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
  {
    start_accept();
  }


private:
  void start_accept()
  {
    session* new_session = new session(io_service_);
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

  void handle_accept(session* new_session,
      const boost::system::error_code& error)
  {
    if (!error)
    {
      new_session->start();
    }
    else
    {
      delete new_session;
    }

    start_accept();
  }

  boost::asio::io_service& io_service_;
  tcp::acceptor acceptor_;
};

int main()
{
  try
  {
    boost::asio::io_service io_service;
    server s(io_service, 4000);

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

  return 0;
}

tcp_client.cpp tcp_client.cpp

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

enum { max_length = 1024 };

int main(int argc, char* argv[])
{
  try
  {


    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(tcp::v4(), "127.0.0.1", "4000");
    tcp::resolver::iterator iterator = resolver.resolve(query);

    tcp::socket s(io_service);
    s.connect(*iterator);

    using namespace std; // For strlen.
    std::cout << "Enter message: ";
    char request[max_length];
    std::cin.getline(request, max_length);
    size_t request_length = strlen(request);
    boost::asio::write(s, boost::asio::buffer(request, request_length));

    char reply[max_length];
    size_t reply_length = boost::asio::read(s,boost::asio::buffer(reply, request_length));
    std::cout << "Reply is: ";
    std::cout.write(reply, reply_length);
    std::cout << "\n";
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

Your comment 你的评论

I think handle_read() calls handle_write() recursively? 我认为handle_read() handle_write()递归调用handle_write()吗?

is close but not quite correct as there is no recursion here. 接近但不太正确,因为此处没有递归。 The documentation explains this nicely: 文档很好地解释了这一点:

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function . 无论异步操作是否立即完成, 都不会从此函数内调用处理程序。 Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post() . 处理程序的调用将以与使用boost::asio::io_service::post()等效的方式执行。

Added emphasis is mine. 重点是我的。 Instead of recursion, It is better to think of these concepts as chaining since one operation such as async_write() is initiated in the handler of another, such as async_read() . 最好将这些概念视为链接,而不是递归,因为一个操作(例如async_write()是在另一个操作(例如async_read()的处理程序中启动的。 The exact specifics depend on the protocol in use. 具体细节取决于所使用的协议。

If you want the server to send the string 0123456789 to the client, fill your buffer before invoking async_write() . 如果要服务器将字符串0123456789发送到客户端,请在调用async_write()之前填充缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM