Here's the code I use:
class Server
{
.....
void Server::accepted()
{
std::cout << "Accepted!" << std::endl;
boost::array<char, 1> buf;
boost::asio::async_read(socket, boost::asio::buffer(buf),
boost::bind(&Server::handleRead, this, buf, boost::asio::placeholders::error));
}
void Server::handleRead(boost::array<char, 1> buf, const boost::system::error_code& error)
{
if(!error)
{
std::cout << "Message: " << buf.data() << std::endl;
}
else
{
std::cout << "Error occurred." << std::endl;
}
}
.....
}
The problem is that I always get the same data from the client: a specific char.
In my client I tried sending other char, but still the server shows the same char.
And when I try to read more than 1 bytes, I get an error that the buf variable is used before it's initialized.
You're using the local variable buf as the read buffer, which is dangerous and won't work. Also, you're just sending the original contents of that buffer to the handler. So instead, you need to use a buffer with a longer lifetime. Something like this:
class Server
{
.....
boost::array<char, 1> buf;
void Server::accepted()
{
std::cout << "Accepted!" << std::endl;
boost::asio::async_read(socket, boost::asio::buffer(buf),
boost::bind(&Server::handleRead, this, boost::asio::placeholders::error));
}
void Server::handleRead(const boost::system::error_code& error)
{
if(!error)
{
std::cout << "Message: " << buf.data() << std::endl;
}
else
{
std::cout << "Error occurred." << std::endl;
}
}
.....
}
edit: or alternatively, using a heap allocated buffer (not sure if the code is right, but you'll get the idea):
void Server::accepted()
{
std::cout << "Accepted!" << std::endl;
boost::shared_ptr<boost::array<char, 1>> buf(new boost::array<char, 1>);
boost::asio::async_read(socket, boost::asio::buffer(*buf),
boost::bind(&Server::handleRead, this, buf, boost::asio::placeholders::error));
}
void Server::handleRead(boost::shared_ptr<boost::array<char, 1>> buf, const boost::system::error_code& error)
{
if(!error)
{
std::cout << "Message: " << buf->data() << std::endl;
}
else
{
std::cout << "Error occurred." << std::endl;
}
}
Related
I'm trying to use serial_port of asio(standlone) to get data from a device. But I can't read even a byte.
I post a screenshoot of the example usage found from documentation website as below :
enter image description here
enter image description here
https://think-async.com/Asio/asio-1.24.0/doc/asio/reference/basic_serial_port/async_read_some.html
There are 3 question I have:
What is the specific type of the first parameter of async_read_some? std::vector<uint8_t>, for example?
How to bind a class member function as the callback/handler?
Is it right that we just make sure io_context.run() run on a background thread and call async_read_some just once?
I'll appreciate it if you guys could help me check out my code or give some advice.
class NmeaSource {
public:
explicit NmeaSource(std::shared_ptr<asio::io_context> io, const nlohmann::json& settings);
void parse();
void handle(const asio::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes read.
);
private:
void open();
std::string m_port;
int m_baudrate;
std::shared_ptr<asio::io_context> m_io;
std::shared_ptr<asio::serial_port> m_serial;
unsigned char m_readBuffer[1024];
};
NmeaSource::NmeaSource(std::shared_ptr<asio::io_context> io, const nlohmann::json& settings)
:m_io(io)
{
try {
setPort(settings.at("port"));
setBaudrate(settings.at("baudrate"));
//LOG("");
std::cout << "port: " << m_port << ", baudrate: " << m_baudrate << std::endl;
}
catch (nlohmann::json::basic_json::type_error& e1) {
std::cout << "type is wrong " << e1.what() << std::endl;
throw e1;
}
catch (nlohmann::json::basic_json::out_of_range& e2) {
std::cout << "key is not found " << e2.what() << std::endl;
throw e2;
}
catch (...)
{
std::cout << "unknown error"<< std::endl;
exit(-1);
}
open();
}
void NmeaSource::open()
{
m_serial = std::make_shared<asio::serial_port>(*m_io);
asio::error_code ec;
m_serial->open(m_port, ec);
if (!ec) {
asio::serial_port_base::baud_rate baudrate(m_baudrate);
m_serial->set_option(baudrate);
std::cout << "successfully" << std::endl;
}
else {
std::cout << "failed " << ec.message() <<std::endl;
}
}
void NmeaSource::handle(const asio::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes read.
)
{
if (!error) {
std::cout << bytes_transferred << " bytes read!" << std::endl;
}
else {
std::cout << error.message() << std::endl;
}
}
void NmeaSource::parse()
{
m_serial->async_read_some(
asio::buffer(m_readBuffer, 1024),
std::bind(&NmeaSource::handle, this,
std::placeholders::_1,
std::placeholders::_2)
);
}
int main()
{
auto io = std::make_shared<asio::io_context>();
//std::thread t(std::bind(static_cast<size_t(asio::io_service::*)()>(&asio::io_service::run), io.get()));
std::thread t([&io]() {io->run(); });
NmeaSource rtk(io, nlohmann::json{ {"port", "COM3"}, {"baudrate", 115200} });
rtk.parse();
for (;;)
{
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
The output
There is a simple example with making use of boost::asio::io_context
https://github.com/unegare/boost-ex/blob/500e46f4d3b41e2abe48e2deccfab39d44ae94e0/main.cpp
#include <boost/asio.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <thread>
#include <vector>
#include <memory>
#include <mutex>
#include <chrono>
#include <iostream>
#include <exception>
std::mutex m_stdout;
class MyWorker {
std::shared_ptr<boost::asio::io_context> io_context;
std::shared_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> work_guard;
public:
MyWorker(std::shared_ptr<boost::asio::io_context> &_io_context, std::shared_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> &_work_guard):
io_context(_io_context), work_guard(_work_guard) {}
MyWorker(const MyWorker &mw): io_context(mw.io_context), work_guard(mw.work_guard) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] MyWorker copy constructor" << std::endl;
m_stdout.unlock();
}
MyWorker(MyWorker &&mw): io_context(std::move(mw.io_context)), work_guard(std::move(mw.work_guard)) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] MyWorker move constructor" << std::endl;
m_stdout.unlock();
}
~MyWorker() {}
void operator() () {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] Thread Start" << std::endl;
m_stdout.unlock();
while(true) {
try {
boost::system::error_code ec;
io_context->run(ec);
if (ec) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] MyWorker: received an error: " << ec << std::endl;
m_stdout.unlock();
continue;
}
break;
} catch (std::exception &ex) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] MyWorker: caught an exception: " << ex.what() << std::endl;
m_stdout.unlock();
}
}
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] Thread Finish" << std::endl;
m_stdout.unlock();
}
};
class Client: public std::enable_shared_from_this<Client> {
std::shared_ptr<boost::asio::io_context> io_context;
std::shared_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> work_guard;
std::shared_ptr<boost::asio::ip::tcp::socket> sock;
std::shared_ptr<std::array<char, 512>> buff;
public:
Client(std::shared_ptr<boost::asio::io_context> &_io_context, std::shared_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> &_work_guard, std::shared_ptr<boost::asio::ip::tcp::socket> &_sock):
io_context(_io_context), work_guard(_work_guard), sock(_sock) {
buff = std::make_shared<std::array<char,512>>();
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] " << __FUNCTION__ << " with args" << std::endl;
m_stdout.unlock();
}
Client(const Client &cl): io_context(cl.io_context), work_guard(cl.work_guard), sock(cl.sock), buff(cl.buff) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] " << __FUNCTION__ << " copy" << std::endl;
m_stdout.unlock();
}
Client(Client &&cl): io_context(std::move(cl.io_context)), work_guard(std::move(cl.work_guard)), sock(std::move(cl.sock)), buff(std::move(cl.buff)) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] " << __FUNCTION__ << " move" << std::endl;
m_stdout.unlock();
}
~Client() {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] " << __FUNCTION__ << " buff.use_count: " << buff.use_count() << " | sock.use_count: " << sock.use_count() << " | io_context.use_count: " << io_context.use_count() << std::endl;
m_stdout.unlock();
}
void OnConnect(const boost::system::error_code &ec) {
std::cout << __FUNCTION__ << std::endl;
if (ec) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] " << __FUNCTION__ << ": " << ec << std::endl;
m_stdout.unlock();
} else {
// buff = std::make_shared<std::array<char, 512>>();
char req[] = "GET / HTTP/1.1\r\nHost: unegare.info\r\n\r\n";
memcpy(buff->data(), req, strlen(req));
m_stdout.lock();
std::cout << req << std::endl;
m_stdout.unlock();
sock->async_write_some(boost::asio::buffer(buff->data(), strlen(buff->data())), std::bind(std::mem_fn(&Client::OnSend), this, std::placeholders::_1, std::placeholders::_2));
}
std::cout << __FUNCTION__ << " use_count: " << buff.use_count() << std::endl;
}
void OnSend(const boost::system::error_code &ec, std::size_t bytes_transferred) {
std::cout << __FUNCTION__ << " use_count: " << io_context.use_count() << std::endl;
if (ec) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] " << __FUNCTION__ << ": " << ec << std::endl;
m_stdout.unlock();
} else {
std::cout << __FUNCTION__ << " use_count: " << buff.use_count() << std::endl;
buff->fill(0);
std::cout << __FUNCTION__ << std::endl;
sock->async_read_some(boost::asio::buffer(buff->data(), buff->size()), std::bind(std::mem_fn(&Client::OnRecv), this, std::placeholders::_1, std::placeholders::_2));
}
}
void OnRecv(const boost::system::error_code &ec, std::size_t bytes_transferred) {
std::cout << __FUNCTION__ << std::endl;
if (ec) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] " << __FUNCTION__ << ": " << ec << std::endl;
m_stdout.unlock();
} else {
m_stdout.lock();
std::cout << buff->data() << std::endl;
m_stdout.unlock();
}
}
};
int main () {
std::shared_ptr<boost::asio::io_context> io_context(std::make_shared<boost::asio::io_context>());
std::shared_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> work_guard(
std::make_shared<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> (boost::asio::make_work_guard(*io_context))
);
MyWorker mw(io_context, work_guard);
std::vector<std::thread> vth;
vth.reserve(1);
for (int i = 1; i > 0; --i) {
vth.emplace_back(mw);
}
std::shared_ptr<Client> cl = 0;
try {
boost::asio::ip::tcp::resolver resolver(*io_context);
boost::asio::ip::tcp::resolver::query query("unegare.info", "80");
boost::asio::ip::tcp::endpoint ep = *resolver.resolve(query);
m_stdout.lock();
std::cout << "ep: " << ep << std::endl;
m_stdout.unlock();
std::shared_ptr<boost::asio::ip::tcp::socket> sock(std::make_shared<boost::asio::ip::tcp::socket>(*io_context));
std::shared_ptr<Client> cl2(std::make_shared<Client>(io_context, work_guard, sock));
cl = cl2->shared_from_this();
m_stdout.lock();
std::cout << "HERE: use_count = " << cl.use_count() << std::endl;
m_stdout.unlock();
sock->async_connect(ep, std::bind(std::mem_fn(&Client::OnConnect), *cl2->shared_from_this(), std::placeholders::_1));
std::this_thread::sleep_for(std::chrono::duration<double>(1));
m_stdout.lock();
std::cout << "AFTER CALL" << std::endl;
m_stdout.unlock();
// asm volatile ("");
} catch (std::exception &ex) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] Main Thread: caught an exception: " << ex.what() << std::endl;
m_stdout.unlock();
}
try {
char t;
std::cin >> t;
work_guard->reset();
// std::this_thread::sleep_for(std::chrono::duration<double>(1));
// std::cout << "Running" << std::endl;
// io_context->run();
} catch (std::exception &ex) {
m_stdout.lock();
std::cout << "[" << std::this_thread::get_id() << "] Main Thread: caught an exception: " << ex.what() << std::endl;
m_stdout.unlock();
}
std::for_each(vth.begin(), vth.end(), std::mem_fn(&std::thread::join));
return 0;
}
stdout:
[140487203505984] MyWorker copy constructor
[140487203505984] MyWorker move constructor
[140487185372928] Thread Start
ep: 95.165.130.37:80
[140487203505984] Client with args
HERE: use_count = 2
[140487203505984] Client copy
[140487203505984] Client move
[140487203505984] ~Client buff.use_count: 0 | sock.use_count: 0 | io_context.use_count: 0
[140487185372928] Client move
[140487185372928] ~Client buff.use_count: 0 | sock.use_count: 0 | io_context.use_count: 0
OnConnect
GET / HTTP/1.1
Host: unegare.info
OnConnect use_count: 2
[140487185372928] ~Client buff.use_count: 2 | sock.use_count: 3 | io_context.use_count: 5
Segmentation Fault (core dumped)
But there is a little problem with the understanding of the segfault caused by the bad reference to the Client object.
But I do not understand why cl2 becomes destructed after the call of
sock->async_connect(ep, std::bind(std::mem_fn(&Client::OnConnect), *cl2->shared_from_this(), std::placeholders::_1));
at the 162 line.
As well as ... Why was there an invocation of the copy constructor?
as it may be noticed from the stdout above.
It's good that you try to understand. However, start simple!
your copy constructor fails to call the base-class copy constructor (!!) oops
your binds bind to
this (which does NOT keep the shared pointer alive)
*cl2->shared_from_this() - oops this binds to a COPY of *cl2 by value¹. That is obviously the reason why that COPY is destructed when you're done
The invalid reference arose from the combination of 1. and 2.b.
I'd suggest to simplify. A lot!
Use Rule Of Zero (only declare special members when you need. In this, you introduced a bug because you did something wrong manually writing a copy-constructor that you didn't need)
Use non-owning references where appropriate (not everything needs to be a smart pointer)
Prefer std::unique_ptr for things that do not require shared ownership (shared ownership should be really rare)
Prefer std::lock_guard instead of manually locking and unlocking (that's not exception safe)
Many others: work_guard doesn't need to be copied, it has a reset() member already, catch by const-reference, if you're gonna catch, don't need to use error_code on io_context::run, check the end-point iterator of resolve before dereference, use boost::asio::connect instead so you don't have to check and iterate over different endpoints etc.
prefer std::string over fixed-size buffers if you're doing dynamic allocation anyways, use non-implementation defined chrono durations (for example 1.0s, not duration<double>(1)), consider using boost::thread_group instead of vector<std::thread> or at least only joining threads that are joinable() etc
Suggest to make that async_connect part of Client, since then you can simply bind members the same way as all the rest of the binds (using shared_from_this(), instead of writing the bug you had)
If you have time left, consider using Beast for the Http request and response creation/parsing
Just as a reference, this is what MyWorker could be:
class MyWorker {
ba::io_context& io_context;
public:
MyWorker(ba::io_context& _io_context) : io_context(_io_context) {}
//// best is to not mention these at all, because even `default`ing can change what compiler generates
//MyWorker(const MyWorker& mw) = default;
//MyWorker(MyWorker&& mw) = default;
//~MyWorker() = default;
void operator()() {
TRACE("Thread Start");
while (true) {
try {
io_context.run();
break; // normal end
} catch (boost::system::system_error const& se) {
TRACE("MyWorker: received an error: " << se.code().message());
} catch (std::exception const& ex) {
TRACE("MyWorker: caught an exception: " << ex.what());
}
}
TRACE("Thread Finish");
}
};
At this point, you could very well just make it a lambda:
auto mw = [&io_context] {
TRACE("Thread Start");
while (true) {
try {
io_context.run();
break; // normal end
} catch (boost::system::system_error const& se) {
TRACE("MyWorker: received an error: " << se.code().message());
} catch (std::exception const& ex) {
TRACE("MyWorker: caught an exception: " << ex.what());
}
}
TRACE("Thread Finish");
};
Much simpler.
The Full Code Simplified
Just see e.g. the simplicity of the new connection code:
void Start() {
tcp::resolver resolver(io_context);
ba::async_connect(sock,
resolver.resolve({"unegare.info", "80"}),
[self=shared_from_this()](error_code ec, tcp::endpoint) { self->OnConnect(ec); });
}
The endpoint is printed when OnConnect is called.
Live On Coliru²
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iomanip>
#include <iostream>
#include <memory>
#include <mutex>
namespace ba = boost::asio;
using ba::ip::tcp;
using namespace std::literals;
static std::mutex s_stdout;
#define TRACE(expr) { \
std::lock_guard<std::mutex> lk(s_stdout); \
std::cout << "[" << std::this_thread::get_id() << "] " << expr << std::endl; \
}
class Client : public std::enable_shared_from_this<Client> {
ba::io_context& io_context;
tcp::socket sock;
std::string buf;
public:
Client(ba::io_context& _io_context) : io_context(_io_context), sock{io_context}
{ }
void Start() {
tcp::resolver resolver(io_context);
ba::async_connect(sock,
resolver.resolve({"unegare.info", "80"}),
std::bind(std::mem_fn(&Client::OnConnect), shared_from_this(), std::placeholders::_1));
}
void OnConnect(const boost::system::error_code& ec) {
TRACE(__FUNCTION__ << " ep:" << sock.remote_endpoint());
if (ec) {
TRACE(__FUNCTION__ << ": " << ec.message());
} else {
buf = "GET / HTTP/1.1\r\nHost: unegare.info\r\n\r\n";
TRACE(std::quoted(buf));
sock.async_write_some(ba::buffer(buf),
std::bind(std::mem_fn(&Client::OnSend), shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
}
void OnSend(const boost::system::error_code& ec, std::size_t bytes_transferred) {
if (ec) {
TRACE(__FUNCTION__ << ": " << ec.message() << " and bytes_transferred: " << bytes_transferred);
} else {
TRACE(__FUNCTION__);
buf.assign(512, '\0');
sock.async_read_some(ba::buffer(buf), std::bind(std::mem_fn(&Client::OnRecv), shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
}
void OnRecv(const boost::system::error_code& ec, std::size_t bytes_transferred) {
TRACE(__FUNCTION__);
if (ec) {
TRACE(__FUNCTION__ << ": " << ec.message() << " and bytes_transferred: " << bytes_transferred);
} else {
buf.resize(bytes_transferred);
TRACE(std::quoted(buf));
}
}
};
int main() {
ba::io_context io_context;
auto work_guard = make_work_guard(io_context);
boost::thread_group vth;
auto mw = [&io_context] {
TRACE("Thread Start");
while (true) {
try {
io_context.run();
break; // normal end
} catch (boost::system::system_error const& se) {
TRACE("MyWorker: received an error: " << se.code().message());
} catch (std::exception const& ex) {
TRACE("MyWorker: caught an exception: " << ex.what());
}
}
TRACE("Thread Finish");
};
vth.create_thread(mw);
try {
std::make_shared<Client>(io_context)->Start();
char t;
std::cin >> t;
work_guard.reset();
} catch (std::exception const& ex) {
TRACE("Main Thread: caught an exception: " << ex.what());
}
vth.join_all();
}
Prints:
[140095938852608] Thread Start
[140095938852608] OnConnect ep:95.165.130.37:80
[140095938852608] "GET / HTTP/1.1
Host: unegare.info
"
[140095938852608] OnSend
[140095938852608] OnRecv
[140095938852608] "HTTP/1.1 200 OK
Date: Sun, 22 Dec 2019 22:26:56 GMT
Server: Apache/2.4.18 (Ubuntu)
Last-Modified: Sun, 10 Mar 2019 10:17:38 GMT
ETag: \"37-583bac3f3c843\"
Accept-Ranges: bytes
Content-Length: 55
Content-Type: text/html
<html>
<head>
</head>
<body>
It works.
</body>
</html>
"
q
[140095938852608] Thread Finish
BONUS
std::bind is obsolete since C++11, consider using lambdas instead. Since Coliru didn't want to co-operate any more, I'll just post the three changed functions in full:
void Start() {
tcp::resolver resolver(io_context);
ba::async_connect(sock,
resolver.resolve({"unegare.info", "80"}),
[self=shared_from_this()](error_code ec, tcp::endpoint) { self->OnConnect(ec); });
}
void OnConnect(const boost::system::error_code& ec) {
TRACE(__FUNCTION__ << " ep:" << sock.remote_endpoint());
if (ec) {
TRACE(__FUNCTION__ << ": " << ec.message());
} else {
buf = "GET / HTTP/1.1\r\nHost: unegare.info\r\n\r\n";
TRACE(std::quoted(buf));
sock.async_write_some(ba::buffer(buf),
[self=shared_from_this()](error_code ec, size_t bytes_transferred) { self->OnSend(ec, bytes_transferred); });
}
}
void OnSend(const boost::system::error_code& ec, std::size_t bytes_transferred) {
if (ec) {
TRACE(__FUNCTION__ << ": " << ec.message() << " and bytes_transferred: " << bytes_transferred);
} else {
TRACE(__FUNCTION__);
buf.assign(512, '\0');
sock.async_read_some(ba::buffer(buf),
[self=shared_from_this()](error_code ec, size_t bytes_transferred) { self->OnRecv(ec, bytes_transferred); });
}
}
¹ Does boost::bind() copy parameters by reference or by value?
² Coliru doesn't allow network access
You don’t track destruction of cl2 with you output: cl2 is std::shared_ptr<Client>. You seem to track construction of Client objects.
You problem is the * in front of cl2->make_shared_from_this(): that will dereference the std::shared_ptr<Client>. The bind() expression sees a Client& and captures a Client by copy. Removing the * should fix the problem. I haven’t fully understood was code is trying to do (I’m reading it on a phone) but I guess you actually want to capture the std::shared_ptr<Client> rather than the Client.
Also, as cl2 is already a std::shared_ptr<Client> there is no point in calling make_shared_from_this() on the pointed to object. It just recreates an unnecessary st::shared_ptr<Client>.
The for loop in main.cpp, which calls a function that uses boost::mutex and that reads from a socket using read_until, only runs once, after that it's like it's blocked. I've tried putting a continue before the closing brackets and then it crashes. It's probably related to threading.
// MAIN.CPP
int main(int argc, char* argv[])
{
std::cout << "Enter port number: ";
std::string port;
std::getline(std::cin, port);
int tempPort = std::stoi(port);
Network * network = new Network(tempPort);
int it = 0;
boost::thread * t1;
t1 = new boost::thread([&network, &it]
{
while (true)
{
boost::asio::ip::tcp::socket * sock = new boost::asio::ip::tcp::socket(network->io_service);
network->accept(*sock);
if (network->socketList.size() > 0)
{
for (boost::asio::ip::tcp::socket * s : network->socketList)
{
if (s->remote_endpoint().address().to_string() == sock->remote_endpoint().address().to_string())
{
continue;
}
else {
network->socketList.push_back(sock);
std::cout << s->remote_endpoint().address().to_string() << " connected." << std::endl;
}
}
}
else {
network->socketList.push_back(sock);
std::cout << sock->remote_endpoint().address().to_string() << " connected." << std::endl;
}
}
});
while (true)
{
for (boost::asio::ip::tcp::socket * sock : network->socketList)
{
std::cout << "on range-based for loop" << std::endl;
network->readChatMessage(*(sock));
}
}
t1->join();
return 0;
}
// NETWORK.CPP
int Network::sendChatMessage(boost::asio::ip::tcp::socket & socket, ChatMessage & message)
{
try
{
boost::system::error_code err;
boost::asio::streambuf buf;
{
std::ostream out(&buf);
boost::archive::text_oarchive oa(out);
oa & message;
std::cout << std::string(message.text.begin(), message.text.end()) << std::endl;
}
m.lock();
write(socket, buf, err);
if (err)
{
std::cout << err.message() << std::endl;
}
m.unlock();
std::cout << "Mensagem enviada com sucesso!" << std::endl;
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
int Network::readChatMessage(boost::asio::ip::tcp::socket & socket)
{
std::cout << "in readChatMessage()" << std::endl;
boost::system::error_code err;
boost::asio::streambuf buf;
m.lock();
boost::asio::read_until(socket, buf, '\0', err);
if (err)
{
std::cout << err.message() << std::endl;
}
m.unlock();
std::istream in(&buf);
ChatMessage message;
boost::archive::text_iarchive ia(in);
ia & message;
std::cout << std::string(message.text.begin(), message.text.end()) << std::endl;
this->sendChatMessage(socket, message);
return 0;
}
I was able to fix the problem after debugging and editing the code a bit, then I was able to see there was an error happening: input stream error due to the serialization Input/Output. I handled the error properly, unlocking the mutex when the error happened and not letting the mutex go undone.
Snippet:
int Network::readChatMessage(boost::asio::ip::tcp::socket & socket)
{
std::cout << "in readChatMessage()" << std::endl;
boost::system::error_code err;
boost::asio::streambuf buf;
m.lock();
boost::asio::read_until(socket, buf, '\0', err);
if (err)
{
m.unlock();
std::cout << err.message() << std::endl;
return 0;
}
else {
m.unlock();
std::istream in(&buf);
ChatMessage message;
boost::archive::text_iarchive ia(in);
ia & message;
std::cout << std::string(message.text.begin(), message.text.end()) << std::endl;
this->sendChatMessage(socket, message);
return 0;
}
m.unlock();
return 0;
}
I want to transfer some files via tcp over lan, and so I wrote the following code for my TX-Part:
void send_data(char * filename, char * dest)
{
try
{
boost::asio::io_service io_service;
char dest_t = *dest;
std::string adr = ip_adr_display[0] + ':' + boost::lexical_cast<std::string>(PORTNUM_TCP_IN);
std::cout << "Adress is: " << adr << " and file is: " << filename << '\n';
if(debugmode)
debug_global << adr << '\n';
std::string file = filename;
async_tcp_client client(io_service, adr, file);
io_service.run();
}
catch(std::exception& e)
{
};
};
and RX-Part:
void rec_data(void)
{
try
{
std::cout << "Receiving data...\n";
async_tcp_server *recv_file_tcp_server = new async_tcp_server(PORTNUM_TCP_IN);
if(debugmode)
debug_global << "Receiving...\n";
delete recv_file_tcp_server;
}
catch(std::exception &e)
{
};
};
with the following server and client code:
using boost::asio::ip::tcp;
class async_tcp_client
{
public:
async_tcp_client(boost::asio::io_service& io_service, const std::string& server, const std::string& path):resolver_(io_service), socket_(io_service)
{
size_t pos = server.find(':');
if(pos==std::string::npos)
return;
std::string port_string = server.substr(pos+1);
std::string server_ip_or_host = server.substr(0,pos);
source_file.open(path.c_str(), std::ios_base::binary|std::ios_base::ate);
if(!source_file)
{
std::cout << "Failed to open " << path << std::endl;
return;
}
size_t file_size = source_file.tellg();
source_file.seekg(0);
std::ostream request_stream(&request_);
request_stream << path << "\n" << file_size << "\n\n";
std::cout << "Request size: " << request_.size() << std::endl;
tcp::resolver::query query(server_ip_or_host, port_string);
resolver_.async_resolve(query, boost::bind(&async_tcp_client::handle_resolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator));
};
private:
void handle_resolve(const boost::system::error_code & err, tcp::resolver::iterator endpoint_iterator)
{
if(!err)
{
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint, boost::bind(&async_tcp_client::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator));
}
else
{
std::cout << "Error: " << err.message() << '\n';
}
};
void handle_connect(const boost::system::error_code &err, tcp::resolver::iterator endpoint_iterator)
{
if(!err)
{
boost::asio::async_write(socket_, request_, boost::bind(&async_tcp_client::handle_write_file, this, boost::asio::placeholders::error));
}
else if(endpoint_iterator != tcp::resolver::iterator())
{
socket_.close();
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint, boost::bind(&async_tcp_client::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator));
}
else
{
std::cout << "Error: " << err.message() << '\n';
};
}
void handle_write_file(const boost::system::error_code& err)
{
if(!err)
{
if(source_file.eof() == false)
{
source_file.read(buf.c_array(), (std::streamsize)buf.size());
if(source_file.gcount()<= 0)
{
std::cout << "read file error" << std::endl;
return;
};
std::cout << "Send " << source_file.gcount() << "bytes, total: " << source_file.tellg() << " bytes.\n";
boost::asio::async_write(socket_, boost::asio::buffer(buf.c_array(), source_file.gcount()),boost::bind(&async_tcp_client::handle_write_file, this, boost::asio::placeholders::error));
if(err)
{
std::cout << "Send error: " << err << std::endl;
return;
}
}
else
return;
}
else
{
std::cout << "Error: " << err.message() << "\n";
}
};
tcp::resolver resolver_;
tcp::socket socket_;
boost::array<char, 1024> buf;
boost::asio::streambuf request_;
std::ifstream source_file;
};
class async_tcp_connection: public boost::enable_shared_from_this<async_tcp_connection>
{
public:
async_tcp_connection(boost::asio::io_service& io_service):socket_(io_service), file_size(0){}
void start()
{
if(debugmode)
debug_global << __FUNCTION__ << std::endl;
async_read_until(socket_, request_buf, "\n\n", boost::bind(&async_tcp_connection::handle_read_request, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
boost::asio::ip::tcp::socket& socket(){return socket_;}
private:
boost::asio::streambuf request_buf;
size_t file_size;
std::ofstream output_file;
boost::asio::ip::tcp::socket socket_;
boost::array<char, 40960> buf;
void handle_read_request(const boost::system::error_code& err, std::size_t bytes_transferred)
{
if(err)
{
return handle_error(__FUNCTION__, err);
}
if(debugmode)
debug_global << __FUNCTION__ << "(" << bytes_transferred << ")" <<", in_avail = " << request_buf.in_avail() << ", size = " << request_buf.size() << ", max_size = " << request_buf.max_size() << ".\n";
std::istream request_stream(&request_buf);
std::string file_path;
request_stream >> file_path;
request_stream >> file_size;
request_stream.read(buf.c_array(), 2);
if(debugmode)
debug_global << file_path << " size is " << file_size << ", tellg = " << request_stream.tellg() << std::endl;
size_t pos = file_path.find_last_of('\\');
if(pos!= std::string::npos)
file_path = file_path.substr(pos+1);
output_file.open(file_path.c_str(), std::ios_base::binary);
if(!output_file)
{
if(debugmode)
debug_global << "Failed to open: " << file_path << std::endl;
return;
}
do{
request_stream.read(buf.c_array(), (std::streamsize)buf.size());
if(debugmode)
debug_global << __FUNCTION__ << " write " << request_stream.gcount() << " bytes.\n";
output_file.write(buf.c_array(), request_stream.gcount());
}while(request_stream.gcount() > 0);
async_read(socket_, boost::asio::buffer(buf.c_array(), buf.size()),boost::bind(&async_tcp_connection::handle_read_file_content, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void handle_read_file_content(const boost::system::error_code& err, std::size_t bytes_transferred)
{
if (bytes_transferred>0)
{
output_file.write(buf.c_array(), (std::streamsize)bytes_transferred);
if(debugmode)
debug_global << __FUNCTION__ << " recv " << output_file.tellp() << " bytes."<< std::endl;
if (output_file.tellp()>=(std::streamsize)file_size)
{
return;
}
}
if (err)
{
return handle_error(__FUNCTION__, err);
}
async_read(socket_, boost::asio::buffer(buf.c_array(), buf.size()), boost::bind(&async_tcp_connection::handle_read_file_content, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void handle_error(const std::string& function_name, const boost::system::error_code& err)
{
if(debugmode)
debug_global << __FUNCTION__ << " in " << function_name <<" due to " << err <<" " << err.message()<< std::endl;
}
};
class async_tcp_server : private boost::noncopyable
{
public:
typedef boost::shared_ptr<async_tcp_connection> ptr_async_tcp_connection;
async_tcp_server(unsigned short port):acceptor_(io_service_, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port), true)
{
ptr_async_tcp_connection new_connection_(new async_tcp_connection(io_service_));
acceptor_.async_accept(new_connection_->socket(), boost::bind(&async_tcp_server::handle_accept, this,new_connection_, boost::asio::placeholders::error));
io_service_.run();
}
void handle_accept(ptr_async_tcp_connection current_connection, const boost::system::error_code& e)
{
if(debugmode)
debug_global << __FUNCTION__ << " " << e << ", " << e.message()<<std::endl;
if (!e)
{
current_connection->start();
//ptr_async_tcp_connection new_connection_(new async_tcp_connection(io_service_));
//acceptor_.async_accept(new_connection_->socket(),
// boost::bind(&async_tcp_server::handle_accept, this,new_connection_,
// boost::asio::placeholders::error));
}
}
~async_tcp_server()
{
io_service_.stop();
}
private:
boost::asio::io_service io_service_;
boost::asio::ip::tcp::acceptor acceptor_;
};
If I want to transmit a file, I have to enter the absolute path (why?), if I enter the relative path (e.g. "Image.jpg"), I get the error message "failed to open Image.jpg".
After successfull calling the function, I get the following output:
Adress is: <ip>:<port> and file is: <full file path>
Request size: 91
Send 1024 bytes, total: 1024 bytes
Send 1024 bytes, total: 2048 bytes
etc..
Send 1024 bytes, total: 20480 bytes
Send 406 bytes, total: -1 bytes (Why?)
At the receiving side, I get no received data. Why? I do not understand why my code is not working...
Thank you very much!
UPDATE In my answer I casually said
I added postfix .received to the output file name to prevent overwriting the source.
I just realized that this is likely your problem:
If you use your code with the receiver on the same machine as the sender, you will overwrite the source file while you are still sending it... OOPS.
So, I fixed up the code just I could run it.
Here's the test main:
int main()
{
boost::thread_group g;
g.create_thread(rec_data); // get the receiver running
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
g.create_thread([] { send_data("test.cpp"); });
g.join_all();
}
I added postfix .received to the output file name to prevent overwriting the source.
When running this, it appears to work reasonably well:
g++ -std=c++11 -Wall -pedantic -pthread test.cpp -lboost_system -lboost_thread
./a.out
md5sum test.cpp test.cpp.received
We get the output
0dc16e7f0dc23cb9fce100d825852621 test.cpp.received
0dc16e7f0dc23cb9fce100d825852621 test.cpp
I've also tested it with a png and with a 93Mb executable.
Full code (also on Coliru, although Coliru doesn't allow network connections):
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <iostream>
#include <fstream>
#include <boost/enable_shared_from_this.hpp>
using boost::asio::ip::tcp;
static bool debugmode = true;
static boost::mutex debug_mutex;
static std::ostream debug_global(std::clog.rdbuf());
class async_tcp_client
{
public:
async_tcp_client(boost::asio::io_service& io_service, const std::string& server, const std::string& path)
: resolver_(io_service), socket_(io_service)
{
size_t pos = server.find(':');
if(pos==std::string::npos)
{
return;
}
std::string port_string = server.substr(pos+1);
std::string server_ip_or_host = server.substr(0,pos);
source_file.open(path, std::ios_base::binary|std::ios_base::ate);
if(!source_file)
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << __LINE__ << "Failed to open " << path << std::endl;
return;
}
size_t file_size = source_file.tellg();
source_file.seekg(0);
std::ostream request_stream(&request_);
request_stream << path << "\n" << file_size << "\n\n";
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << "Request size: " << request_.size() << std::endl;
}
tcp::resolver::query query(server_ip_or_host, port_string);
resolver_.async_resolve(query, boost::bind(&async_tcp_client::handle_resolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator));
};
private:
void handle_resolve(const boost::system::error_code & err, tcp::resolver::iterator endpoint_iterator)
{
if(!err)
{
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint, boost::bind(&async_tcp_client::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator));
}
else
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << "Error: " << err.message() << '\n';
}
};
void handle_connect(const boost::system::error_code &err, tcp::resolver::iterator endpoint_iterator)
{
if(!err)
{
boost::asio::async_write(socket_, request_, boost::bind(&async_tcp_client::handle_write_file, this, boost::asio::placeholders::error));
}
else if(endpoint_iterator != tcp::resolver::iterator())
{
socket_.close();
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint, boost::bind(&async_tcp_client::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator));
}
else
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << "Error: " << err.message() << '\n';
};
}
void handle_write_file(const boost::system::error_code& err)
{
if(!err)
{
if(source_file)
//if(source_file.eof() == false)
{
source_file.read(buf.c_array(), (std::streamsize)buf.size());
if(source_file.gcount()<= 0)
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << "read file error" << std::endl;
return;
};
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << "Send " << source_file.gcount() << "bytes, total: " << source_file.tellg() << " bytes.\n";
}
boost::asio::async_write(socket_, boost::asio::buffer(buf.c_array(), source_file.gcount()),boost::bind(&async_tcp_client::handle_write_file, this, boost::asio::placeholders::error));
}
else
{
return;
}
}
else
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << "Error: " << err.message() << "\n";
}
};
tcp::resolver resolver_;
tcp::socket socket_;
boost::array<char, 1024> buf;
boost::asio::streambuf request_;
std::ifstream source_file;
};
class async_tcp_connection: public boost::enable_shared_from_this<async_tcp_connection>
{
public:
async_tcp_connection(boost::asio::io_service& io_service)
: socket_(io_service), file_size(0)
{
}
void start()
{
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << __FUNCTION__ << std::endl;
}
async_read_until(socket_, request_buf, "\n\n", boost::bind(&async_tcp_connection::handle_read_request, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
boost::asio::ip::tcp::socket& socket()
{
return socket_;
}
private:
boost::asio::streambuf request_buf;
std::ofstream output_file;
boost::asio::ip::tcp::socket socket_;
size_t file_size;
boost::array<char, 40960> buf;
void handle_read_request(const boost::system::error_code& err, std::size_t bytes_transferred)
{
if(err)
{
return handle_error(__FUNCTION__, err);
}
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << __FUNCTION__ << "(" << bytes_transferred << ")" <<", in_avail = " << request_buf.in_avail() << ", size = " << request_buf.size() << ", max_size = " << request_buf.max_size() << ".\n";
}
std::istream request_stream(&request_buf);
std::string file_path;
request_stream >> file_path;
request_stream >> file_size;
request_stream.read(buf.c_array(), 2);
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << file_path << " size is " << file_size << ", tellg = " << request_stream.tellg() << std::endl;
}
size_t pos = file_path.find_last_of('\\');
if(pos!= std::string::npos)
{
file_path = file_path.substr(pos+1);
}
output_file.open(file_path + ".received", std::ios_base::binary);
if(!output_file)
{
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << __LINE__ << "Failed to open: " << file_path << std::endl;
}
return;
}
do
{
request_stream.read(buf.c_array(), (std::streamsize)buf.size());
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << __FUNCTION__ << " write " << request_stream.gcount() << " bytes.\n";
}
output_file.write(buf.c_array(), request_stream.gcount());
}
while(request_stream.gcount() > 0);
async_read(socket_, boost::asio::buffer(buf.c_array(), buf.size()),boost::bind(&async_tcp_connection::handle_read_file_content, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void handle_read_file_content(const boost::system::error_code& err, std::size_t bytes_transferred)
{
if (bytes_transferred>0)
{
output_file.write(buf.c_array(), (std::streamsize)bytes_transferred);
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << __FUNCTION__ << " recv " << output_file.tellp() << " bytes."<< std::endl;
}
if (output_file.tellp()>=(std::streamsize)file_size)
{
return;
}
}
if (err)
{
return handle_error(__FUNCTION__, err);
}
async_read(socket_, boost::asio::buffer(buf.c_array(), buf.size()), boost::bind(&async_tcp_connection::handle_read_file_content, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void handle_error(const std::string& function_name, const boost::system::error_code& err)
{
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << __FUNCTION__ << " in " << function_name <<" due to " << err <<" " << err.message()<< std::endl;
}
}
};
class async_tcp_server : private boost::noncopyable
{
public:
typedef boost::shared_ptr<async_tcp_connection> ptr_async_tcp_connection;
async_tcp_server(unsigned short port):acceptor_(io_service_, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port), true)
{
ptr_async_tcp_connection new_connection_(new async_tcp_connection(io_service_));
acceptor_.async_accept(new_connection_->socket(), boost::bind(&async_tcp_server::handle_accept, this,new_connection_, boost::asio::placeholders::error));
io_service_.run();
}
void handle_accept(ptr_async_tcp_connection current_connection, const boost::system::error_code& e)
{
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << __FUNCTION__ << " " << e << ", " << e.message()<<std::endl;
}
if (!e)
{
current_connection->start();
}
}
~async_tcp_server()
{
io_service_.stop();
}
private:
boost::asio::io_service io_service_;
boost::asio::ip::tcp::acceptor acceptor_;
};
void send_data(std::string const& filename, std::string const& adr = "localhost:6767")
{
try
{
boost::asio::io_service io_service;
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << "Adress is: " << adr << " and file is: " << filename << '\n';
}
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << adr << '\n';
}
async_tcp_client client(io_service, adr, filename);
io_service.run();
}
catch(std::exception const& e)
{
std::cerr << "Exception in " << __PRETTY_FUNCTION__ << ": " << e.what() << "\n";
};
};
void rec_data(void)
{
try
{
{
boost::mutex::scoped_lock lk(debug_mutex);
std::cout << "Receiving data...\n";
}
async_tcp_server recv_file_tcp_server(6767);
if(debugmode)
{
boost::mutex::scoped_lock lk(debug_mutex);
debug_global << "Received\n";
}
}
catch(std::exception const& e)
{
std::cerr << "Exception in " << __PRETTY_FUNCTION__ << ": " << e.what() << "\n";
};
};
int main()
{
boost::thread_group g;
g.create_thread(rec_data); // get the receiver running
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
g.create_thread([] { send_data("main.cpp"); });
g.join_all();
}
I am having a problem while creating a client program that sends requests. The request are using keep alive TCP HTTP connections. When a connection is closed(due to timeout or max being hit), I try and start a new connection if none are available, and resend the request. The connect works fine however, when I try and send the write, nothing is sent(according to Wireshark), but my error code for the write was a success. The receiving server does not receive any information either. Here is the main parts of my code:
void request_handler::send_1(std::vector<std::string> *bid_vector, std::string request_path, boost::mutex *bids_mutex)
{
try
{
boost::asio::streambuf request;
std::ostream request_stream(&request);
std::string reply_information;
request_stream << "GET /tests HTTP/1.1\r\n";
request_stream << "Host: 10.1.10.160\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: keep-alive\r\n\r\n";
server1_mutex_.lock();
if(server1_available_map_.size() == 0)
{
server1_mutex_.unlock();
persistent_connection *new_connection = new persistent_connection("10.1.10.160","80");
if(new_connection->send(request, reply_information))
{
server1_mutex_.lock();
server1_available_map_[new_connection->get_id()] = new_connection;
server1_mutex_.unlock();
}
}
else
{
persistent_connection *current_connection = (*(server1_available_map_.begin())).second;
server1_available_map_.erase(current_connection->get_id());
server1_mutex_.unlock();
int retry_counter = 20;
while(!current_connection->query_rtb(request, reply_information) && --retry_counter != 0)
{
delete current_connection;
server1_mutex_.lock();
if(server1_available_map_.size() == 0)
{
server1_mutex_.unlock();
current_connection = new persistent_connection("10.1.10.160","80");
}
else
{
current_connection = (*(server1_available_map_.begin())).second;
server1_available_map_.erase(current_connection->get_id());
server1_mutex_.unlock();
}
}
//Could not connect to 20 connections
if(retry_counter == 0)
{
Log::fatal("Could not connect in 20 tries");
delete current_connection;
return;
}
server1_mutex_.lock();
server1_available_map_[current_connection->get_id()] = current_connection;
server1_mutex_.unlock();
}
bids_mutex->lock();
bid_vector->push_back(reply_information);
bids_mutex->unlock();
}
catch(boost::thread_interrupted& e)
{
std::cout << "before cancel 1" << std::endl;
return;
}
catch(...)
{
std::cout << "blah blah blah" << std::endl;
}
}
And my persistent_connection class
persistent_connection::persistent_connection(std::string ip, std::string port):
io_service_(), socket_(io_service_), host_ip_(ip)
{
boost::uuids::uuid uuid = boost::uuids::random_generator()();
id_ = boost::lexical_cast<std::string>(uuid);
boost::asio::ip::tcp::resolver resolver(io_service_);
boost::asio::ip::tcp::resolver::query query(host_ip_,port);
boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query);
boost::asio::ip::tcp::endpoint endpoint = *iterator;
socket_.async_connect(endpoint, boost::bind(&persistent_connection::handler_connect, this, boost::asio::placeholders::error, iterator));
io_service_.run();
}
void persistent_connection::handler_connect(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator endpoint_iterator)
{
if(ec)
{
std::cout << "Couldn't connect" << ec << std::endl;
return;
}
else
{
boost::asio::socket_base::keep_alive keep_option(true);
socket_.set_option(keep_option);
std::cout << "Connect handler" << std::endl;
}
}
bool persistent_connection::send(boost::asio::streambuf &request_information, std::string &reply_information)
{
std::cout << "DOING QUERY in " << id_ << std::endl;
boost::system::error_code write_ec, read_ec;
try
{
std::cout << "Before write" << std::endl;
boost::asio::write(socket_, request_information, write_ec);
std::cout << write_ec.message() << std::endl;
}catch(std::exception& e)
{
std::cout << "Write exception: " << e.what() << std::endl;
}
if(write_ec)
{
std::cout <<"Write error: " << write_ec.message() << std::endl;
return false;
}
boost::array<char,8192> buf;
buf.assign(0);
try
{
std::cout << "Before read" << std::endl;
boost::asio::read(socket_, boost::asio::buffer(buf), boost::asio::transfer_at_least(1), read_ec);
std::cout << read_ec.message() << std::endl;
}catch(std::exception& e)
{
std::cout << "Read exception: " << e.what() << std::endl;
}
if(read_ec)
{
std::cout << "Read error: " << read_ec.message() << std::endl;
return false;
}
reply_information = buf.data();
return true;
}
std::string persistent_connection::get_id()
{
return id_;
}
The path for this to happen is if server1_available_map_.size() > 0, and if the while executes, and fails. And then if the size == 0 on the second server1_available_map_.size();
The output for the call is:
DOING QUERY in 69a8f0ab-2a06-45b4-be26-37aea6d93ff2
Before write
Success
Before read
End of file
Read error: End of file
Connect handler
DOING QUERY in 4eacaa96-1040-4878-8bf5-c29b87fa1232
Before write
Success
Before read
Which shows that the first connection gets an end of file(connection closed by server on other end). The second connection connects fine(Connect handler message), and the query is executed in the second connection(different id), and the write is apparently successful, and the program hangs on the read(because there is nothing to read).
Does anyone have any idea why this would be happening? Is there something I seem to be doing wrong?
Thank you
It looks like you are passing the same boost::asio::streambuf to multiple write calls.
boost::asio::write(socket_, request_information, write_ec);
The contents of the buffer are consumed by the first call to boost::asio::write. This effectively empties the buffer so that there is nothing left to send. Pass a const string if you want to use the same buffer for multiple writes.