Ignis Zephyrus Ignis Zephyrus - 11 months ago 170
C++ Question

Boost asio, async_read and acync_write not calling callbacks

I'm encapsulating the

boost-asio
socket, but I got an issue with it, but neither
async_read
nor
async_write
calls their callback function and I don't understand why.

I've tried using
async_read_some
but had the same issue.

Here's the code I've written so far

#include <iostream>
#include "socket.hpp"

Socket::Socket()
{
boost::asio::ip::tcp::endpoint ep_tmp(boost::asio::ip::tcp::v4(), 4242);

endpoint = ep_tmp;
acceptor = new boost::asio::ip::tcp::acceptor(ios, endpoint);
tcp_socket = new boost::asio::ip::tcp::socket(ios);
acceptor->listen();
}

Socket::~Socket()
{
delete(acceptor);
delete(tcp_socket);
}

void Socket::get_connection()
{
acceptor->async_accept(*tcp_socket, [](const boost::system::error_code &ec)
{
std::cout << "Connection received." << std::endl;
if (ec)
std::cout << "Error " << ec << std::endl;
});
this->exec();
}

void Socket::send(std::string &message)
{
async_write(*tcp_socket, boost::asio::buffer(message),
[](const boost::system::error_code &ec,
std::size_t bytes_transferred)
{
std::cout << "Sending datas." << std::endl;
if (ec)
std::cout << "Error " << ec << std::endl;
else
std::cout << bytes_transferred << " bytes transferred." << std::endl;
});
}

void Socket::receive(void)
{
char *buf;

buf = (char *)malloc(sizeof(char) * 50);
buf = (char *)memset(buf, 0, 50);
async_read(*tcp_socket, boost::asio::buffer(buf, 50),
[](const boost::system::error_code &ec,
std::size_t bytes_transferred)
{
std::cout << "Receiving datas." << std::endl;
if (ec)
std::cout << "Error " << ec << std::endl;
else
std::cout << bytes_transferred
<< " bytes transferred." << std::endl;
});
}

void Socket::exec(void)
{
ios.run();
}

int main()
{
Socket serv;
std::string data_test;

data_test = "Test\n";
serv.get_connection();
serv.send(data_test);
serv.exec();
serv.receive();
serv.exec();
return (0);
}


The
malloc
bit is temporary until I find a way to do it without using C.

I'd be really thankful if someone could enlighten me on that issue

Answer Source

You have to call io_service::reset before second and later calls to io_service::run. And you probably want to use synchronous API instead, as your current approach absolutely defeats the purpose of asynchronicity.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download