logo
down
shadow

boost::asio usage in self-contained class


boost::asio usage in self-contained class

By : user4578022
Date : November 22 2020, 02:59 PM
like below fixes the issue Is this what you're after:
Move the io_service into the class (not by reference). And all usages as well.
code :
#include <cstdlib>
#include <deque>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "chat_message.hpp"

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

typedef std::deque<chat_message> chat_message_queue;

class chat_client
{
public:
  chat_client(std::string host, std::string portorservice)
    : io_service_(),
      thread_(boost::bind(&boost::asio::io_service::run, &io_service_)),
      socket_(io_service_)
  {
    tcp::resolver resolver(io_service_);
    tcp::resolver::query query(host, portorservice);
    tcp::resolver::iterator iterator = resolver.resolve(query);

    boost::asio::async_connect(socket_, iterator,
        boost::bind(&chat_client::handle_connect, this,
          boost::asio::placeholders::error));
  }

  void write(const chat_message& msg)
  {
    io_service_.post(boost::bind(&chat_client::do_write, this, msg));
  }

  void close()
  {
    io_service_.post(boost::bind(&chat_client::do_close, this));
  }

  ~chat_client() {
    close();
    if (thread_.joinable())
        thread_.join();
  }

private:

  void handle_connect(const boost::system::error_code& error)
  {
    if (!error)
    {
      boost::asio::async_read(socket_,
          boost::asio::buffer(read_msg_.data(), chat_message::header_length),
          boost::bind(&chat_client::handle_read_header, this,
            boost::asio::placeholders::error));
    }
  }

  void handle_read_header(const boost::system::error_code& error)
  {
    if (!error && read_msg_.decode_header())
    {
      boost::asio::async_read(socket_,
          boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
          boost::bind(&chat_client::handle_read_body, this,
            boost::asio::placeholders::error));
    }
    else
    {
      do_close();
    }
  }

  void handle_read_body(const boost::system::error_code& error)
  {
    if (!error)
    {
      std::cout.write(read_msg_.body(), read_msg_.body_length());
      std::cout << "\n";
      boost::asio::async_read(socket_,
          boost::asio::buffer(read_msg_.data(), chat_message::header_length),
          boost::bind(&chat_client::handle_read_header, this,
            boost::asio::placeholders::error));
    }
    else
    {
      do_close();
    }
  }

  void do_write(chat_message msg)
  {
    bool write_in_progress = !write_msgs_.empty();
    write_msgs_.push_back(msg);
    if (!write_in_progress)
    {
      boost::asio::async_write(socket_,
          boost::asio::buffer(write_msgs_.front().data(),
            write_msgs_.front().length()),
          boost::bind(&chat_client::handle_write, this,
            boost::asio::placeholders::error));
    }
  }

  void handle_write(const boost::system::error_code& error)
  {
    if (!error)
    {
      write_msgs_.pop_front();
      if (!write_msgs_.empty())
      {
        boost::asio::async_write(socket_,
            boost::asio::buffer(write_msgs_.front().data(),
              write_msgs_.front().length()),
            boost::bind(&chat_client::handle_write, this,
              boost::asio::placeholders::error));
      }
    }
    else
    {
      do_close();
    }
  }

  void do_close()
  {
    socket_.close();
  }

private:
  boost::asio::io_service io_service_;
  boost::thread thread_;
  tcp::socket socket_;
  chat_message read_msg_;
  chat_message_queue write_msgs_;
};

int main(int argc, char* argv[])
{
    try
    {
        if (argc != 3)
        {
            std::cerr << "Usage: chat_client <host> <port>\n";
            return 1;
        }

        chat_client c(argv[1], argv[2]);

        char line[chat_message::max_body_length + 1];
        while (std::cin.getline(line, chat_message::max_body_length + 1))
        {
            using namespace std; // For strlen and memcpy.
            chat_message msg;
            msg.body_length(strlen(line));
            memcpy(msg.body(), line, msg.body_length());
            msg.encode_header();
            c.write(msg);
        }

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


Share : facebook icon twitter icon
error: no type named 'const_iterator' in 'class boost::asio::mutable_buffer' when trying to read using boost::asio::asyn

error: no type named 'const_iterator' in 'class boost::asio::mutable_buffer' when trying to read using boost::asio::asyn


By : C Sunil Reddy
Date : March 29 2020, 07:55 AM
it should still fix some issue The buffer parameter given to the async_read() free function needs to meet the MutableBuffer sequence requirements. You should use mutable_buffers_1 instead of mutable_buffer.
code :
void Connection::asyncReceiveHeader()
{
    Buffer* header = new Buffer(packetHeaderSize);
    ba::mutable_buffers_1 buffer = ba::buffer(header->pointer(), header->size());
    auto readHandler = bind(&Connection::headerReceived, this, ba::placeholders::error, ba::placeholders::bytes_transferred, header);

    ba::async_read(socket, buffer, readHandler);
}
Callback passed to boost::asio::async_read_some never invoked in usage where boost::asio::read_some returns data

Callback passed to boost::asio::async_read_some never invoked in usage where boost::asio::read_some returns data


By : gpepper
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The code does not guarantee that the io_service is running. io_service::run() will return when either:
All work has finished and there are no more handlers to be dispatched The io_service has been stopped.
code :
boost::bind(..., boost::ref(finished_reading), boost::ref(ec),
            boost::ref(bytes_read));
boost::asio::read throws compilation error 'read_some' is not a member of 'boost::shared_ptr<boost::asio::ip::tcp::so

boost::asio::read throws compilation error 'read_some' is not a member of 'boost::shared_ptr<boost::asio::ip::tcp::so


By : user2856203
Date : March 29 2020, 07:55 AM
Hope that helps I am trying to build up a client to get data via a specific protocol from a server. I know that my code is not the best - but at the moment I am still experimenting with the basic functions of Boost ASIO. , Okey, I've just found the problem.
code :
// creating socket
  boost::shared_ptr<boost::asio::ip::tcp::socket>   socket(new boost::asio::ip::tcp::socket(*io_service));
  boost::asio::async_read(*socket, boost::asio::buffer(receiveCommandHeader.buffer, receiveCommandHeader.length),
    boost::asio::transfer_all(), boost::bind(HandleRead, ec));
What's wrong with this boost::asio and boost::coroutine usage pattern?

What's wrong with this boost::asio and boost::coroutine usage pattern?


By : user0086
Date : March 29 2020, 07:55 AM
like below fixes the issue It seems that all valgrind errors are caused because of BOOST_USE_VALGRIND macro is not defined as Tanner Sansbury points in comment related to this question. It seems that except this the program is correct.
How to accept boost::asio::ssl::stream<boost::asio::ip::tcp::socket> as an argument of type boost::asio::ip::tcp::

How to accept boost::asio::ssl::stream<boost::asio::ip::tcp::socket> as an argument of type boost::asio::ip::tcp::


By : K.Nelson
Date : March 29 2020, 07:55 AM
To fix this issue Try using lowest_layer() instead of next layer.
For example, this asio HTTP library uses"templates everywhere" and connects an SSL socket with the following code:
code :
void connect_socket(ConnectHandler connect_handler,
                    ASIO::ip::tcp::resolver::iterator host_iterator)
{ ASIO::async_connect(socket_.lowest_layer(), host_iterator, connect_handler); }
Related Posts Related Posts :
  • How to avoid littering header files with std::
  • OpenGL GL_UNPACK_ALIGNMENT
  • Why is this program not working? (Program to copy contents of file to another)
  • Difference between DBus and other Interprocess Communications method
  • How to fill a part of a multidimensional array in C++?
  • C++ SFML Game programming linkage error
  • How do GTK and Qt integrate with Linux in comparison to how they integrate with Windows and OS X?
  • Complexity analysis of loop with limited looping time
  • Boost test fails with enum classes inside namespaces
  • is this a function declaration?
  • Socket recv() one byte at a time
  • C++ Glibc Detected error. Double Free or corruption
  • OpenCV - How to write IplImage array in Mat form?
  • Qt event when anything changed on the window/screen + Screenshot
  • OpenGL Linker error, linking with uncompiled shader
  • Find 4 specific corner pixels and use them with warp perspective
  • Cin Execution Not Working (program.exe < filewithdata.txt)
  • cudaMallocManaged causes Access Violation
  • How to correctly read a value from stdin into a variable
  • Binary Search Tree Forgetting Every Node I Add
  • C++ Return Value from function not same as that value in function
  • Microsoft Visual Studio C++, OpenCV animation
  • C++ function pointer syntax. Why does (*) work but * not?
  • C++: Template class binary operator overloading - seg fault?
  • Passing buffer between two terminals (Named Pipe)
  • C++ parse sub-string to integer
  • Create stereo context for modern opengl
  • Memory leak, when using GLM
  • Get Control under cursor
  • Is this proper behavior? std::map iterator invalidation
  • 2D isometric engine - Math problems - Cube selection - diamond shape map
  • Open second window in Qt
  • Stack Overflow error with Vectors
  • Pure Virtual Friend Class
  • Object initialization syntax in C++
  • Variable undefined error
  • C++ tolower/toupper char pointer
  • Overhead with std::function
  • Is there a way to make a loop that get user input but doesn't stop if the user doesn't input anything?
  • OpenCV in cmake-based project: checking for contrib modules
  • shared_ptr vs unique_ptr uses in classes and children
  • MFC dialog Border padding changed after switching from VS2010 to 2012 or later
  • String rotator in C++ (bitwise rotation)
  • Custom sort vector of pair based on their values
  • Pointer to const overloaded member function
  • how to avoid this for-loop mess in c++?
  • Can the state of a standard C++ iostream manipulator be polled?
  • How to make sure a data type is as large as it needs to be in C++
  • Why is my first ofstream output in my else block missing the fill character?
  • Returning static/ normal arrays in recursion/another function
  • c++, why use const std::string & parameterName?
  • expression did not evaluate to a constant in C++ VS
  • Owner object that takes pre-created values ? Wrong design?
  • Cannot use Macro in a C++ constructor?
  • vector is loosing mat4 information
  • Invalid declarator before with map of struct?
  • std::initializer_list to return member variables returns incorrect values
  • Unable to use Boost + Qt in Mac
  • Passing template function and overload as function argument
  • non standard extension warning when searching in a vector of unique_ptrs
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co