I am using boost::asio::io_service to manage some asynchronous TCP communication. The asio version is boost::asio 1.46. I want to make the client reconnect to the server when the server goes down.
Code follows:
tot_client::tot_client(boost::asio::io_service& io_service,
tcp::resolver::iterator endpoint_iterator)
: io_service_(io_service),
socket_(io_service)
{
boost::shared_ptr<tcp::socket> ptr_temp(new tcp::socket(io_service));
socket_ptr =ptr_temp;
socket_ptr->async_connect(tcp::endpoint(boost::asio::ip::address_v4::loopback(),2012),
boost::bind(&tot_client::handle_connect, this,
boost::asio::placeholders::error));
}
if the server is down, my client checks if the socket is open. If the socket isn't open, it then tries to reconnect to the server:
if(socket_ptr.use_count()&&socket_ptr->is_open())
{
//...
} else
{
reconnect ();
}
The reconnect code is here:
void tot_client::reconnect()
{
try
{
std::cout<<" socket_ptr.reset(new tcp::socket(io_service_) ); "<<endl;
socket_ptr.reset(new tcp::socket(io_service_) );
//socket_ptr->connect(tcp::endpoint(boost::asio::ip::address_v4::loopback(),2012));
socket_ptr->async_connect(tcp::endpoint(boost::asio::ip::address_v4::loopback(),2012),
boost::bind(&tot_client::handle_connect, this,
boost::asio::placeholders::error));
}
catch (std::exception& e )
{
std::cerr<<e.what()<<endl;
}
}
The socket async_connect doesn't work! If I directly use the connect method, the server can receive the socket, but the io_service in the client doesn't work anyway.
Can someone tell me the right way to reconnect to the server? Thanks a lot!
Are you sure io_service is still running?
if io_service stopped working after it ran out of work, you need to call
io_service.reset();
io_service.run();
Related
I am trying to write a very elegant way of handling a reconnect loop with boost async_connect(...). The problem is, I don't see a way how I could elegantly solve the following problem:
I have a TCP client that should try to connect asynchronously to a server, if the connection fails because the server is offline or any other error occurs, wait a given amount of time and try to reconnect. There are multiple things to take into consideration here:
Avoidance of global variables if possible
It has to be async connect
A very basic client is instantiated like so:
tcpclient::tcpclient(std::string host, int port) : _endpoint(boost::asio::ip::address::from_string(host), port), _socket(_ios) {
logger::log_info("Initiating client ...");
}
Attempt to connect to the server:
void tcpclient::start() {
bool is_connected = false;
while (!is_connected) {
_socket.async_connect(_endpoint, connect_handler);
_ios.run();
}
// read write data (?)
}
The handler:
void tcpclient::connect_handler(const boost::system::error_code &error) {
if(error){
// trigger disconnect (?)
logger::log_error(error.message());
return;
}
// Connection is established at this point
// Update timer state and start authentication on server ?
logger::log_info("Connected?");
}
How can I properly start reconnecting everytime the connection fails (or is dropped)? Since the handler is static I can not modify a class attribute that indicates the connection status? I want to avoid using hacky global variable workarounds.
How can I solve this issue in a proper way?
My attempt would be something like this:
tcpclient.h
enum ConnectionStatus{
NOT_CONNECTED,
CONNECTED
};
class tcpclient {
public:
tcpclient(std::string host, int port);
void start();
private:
ConnectionStatus _status = NOT_CONNECTED;
void connect_handler(const boost::system::error_code& error);
boost::asio::io_service _ios;
boost::asio::ip::tcp::endpoint _endpoint;
boost::asio::ip::tcp::socket _socket;
};
tcpclient.cpp
#include "tcpclient.h"
#include <boost/chrono.hpp>
#include "../utils/logger.h"
tcpclient::tcpclient(std::string host, int port) : _endpoint(boost::asio::ip::address::from_string(host), port),
_socket(_ios) {
logger::log_info("Initiating client ...");
logger::log_info("Server endpoint: " + _endpoint.address().to_string());
}
void tcpclient::connect_handler(const boost::system::error_code &error) {
if(!error){
_status = CONNECTED;
logger::log_info("Connected.");
}
else{
_status = NOT_CONNECTED;
logger::log_info("Failed to connect");
_socket.close();
}
}
void tcpclient::start() {
while (_status == NOT_CONNECTED) {
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
_socket.close();
_socket.async_connect(_endpoint, std::bind(&tcpclient::connect_handler, this, std::placeholders::_1));
_ios.run();
}
}
The problem is that the reconnect is not working properly and the application seems to freeze for some reason? Aside from that reconnecting also seems problematic once a connection was established and is then dropped (e.g. due to the server crashing/closing).
std::this_thread::sleep_for(std::chrono::milliseconds(2000)); will freeze program for 2 seconds. What can you do here is to launch async timer when connection attempt fails:
::boost::asio::steady_timer m_timer{_ios, boost::asio::chrono::seconds{2}};
void tcpclient::connect_handler(const boost::system::error_code &error)
{
if(!error)
{
_status = CONNECTED;
logger::log_info("Connected.");
}
else
{
_status = NOT_CONNECTED;
logger::log_info("Failed to connect");
_socket.close();
m_timer.expires_from_now(boost::asio::chrono::seconds{2});
m_timer.async_wait(std::bind(&tcpclient::on_ready_to_reconnect, this, std::placeholders::_1));
}
}
void tcpclient::on_ready_to_reconnect(const boost::system::error_code &error)
{
try_connect();
}
void tcpclient::try_connect()
{
m_socket.async_connect(_endpoint, std::bind(&tcpclient::connect_handler, this, std::placeholders::_1));
}
void tcpclient::start()
{
try_connect();
_ios.run();
}
There is also no need for while (_status == NOT_CONNECTED) loop, because io service will be busy and _ios.run(); won't return until connection is established.
I currently use Windows 7 64bit, MSVC2010 and Boost.Asio 1.57. I would like to connect to a TCP server with a timeout. If the timeout expires, I should close the connection as soon as possible as the IP address (chosen by a user) is probably wrong.
I know I should use async requests because sync requests have no timeouts options included. So I'm using async_connect with an external timeout. This is a solution I have found in many places, including stackoverflow.
The problem is that the following code does not behave like I wished. async_connect is not "cancelled" by the socket.close(). With my computer, closing the socket takes about 15 seconds to complete, which makes my program not responsive for a while...
I would like to have a decent timeout (approx. 3 seconds) and close the socket after this time, so that the user can try to connect with another IP address (from the HMI)
#include <iostream>
#include <boost\asio.hpp>
#include <boost\shared_ptr.hpp>
#include <boost\bind.hpp>
using boost::asio::ip::tcp;
class tcp_client
{
public:
tcp_client(boost::asio::io_service& io_service, tcp::endpoint& endpoint, long long timeout = 3000000)
:m_io_service (io_service),
m_endpoint(endpoint),
m_timer(io_service),
m_timeout(timeout)
{
connect();
}
void stop()
{
m_socket->close();
}
private:
void connect()
{
m_socket.reset(new tcp::socket(m_io_service));
std::cout << "TCP Connection in progress" << std::endl;
m_socket->async_connect(m_endpoint,
boost::bind(&tcp_client::handle_connect, this,
m_socket,
boost::asio::placeholders::error)
);
m_timer.expires_from_now(boost::posix_time::microseconds(m_timeout));
m_timer.async_wait(boost::bind(&tcp_client::HandleWait, this, boost::asio::placeholders::error));
}
void handle_connect(boost::shared_ptr<tcp::socket> socket, const boost::system::error_code& error)
{
if (!error)
{
std::cout << "TCP Connection : connected !" << std::endl;
m_timer.expires_at(boost::posix_time::pos_infin); // Stop the timer !
// Read normally
}
else
{
std::cout << "TCP Connection failed" << std::endl;
}
}
public:
void HandleWait(const boost::system::error_code& error)
{
if (!error)
{
std::cout << "Connection not established..." << std::endl;
std::cout << "Trying to close socket..." << std::endl;
stop();
return;
}
}
boost::asio::io_service& m_io_service;
boost::shared_ptr<tcp::socket> m_socket;
tcp::endpoint m_endpoint;
boost::asio::deadline_timer m_timer;
long long m_timeout;
};
int main()
{
boost::asio::io_service io_service;
tcp::endpoint endpoint(boost::asio::ip::address_v4::from_string("192.168.10.74"), 7171); // invalid address
tcp_client tcpc(io_service, endpoint);
io_service.run();
system("pause");
}
The only solution I found is to run io_service:run() in many threads, and create a new socket for each connection. But this solution does not appear valid to me as I have to specify a number of threads and I don't know how many wrong address the user will enter in my HMI. Yes, some users are not as clever as others...
What's wrong with my code ? How do I interrupt a TCP connection in a clean and fast way ?
Best regards,
Poukill
There's nothing elementary wrong with the code, and it does exactly what you desire on my Linux box:
TCP Connection in progress
Connection not established...
Trying to close socket...
TCP Connection failed
real 0m3.003s
user 0m0.002s
sys 0m0.000s
Notes:
You may have success adding a cancel() call to the stop() function:
void stop()
{
m_socket->cancel();
m_socket->close();
}
You should check for abortion of the timeout though:
void HandleWait(const boost::system::error_code& error)
{
if (error && error != boost::asio::error::operation_aborted)
{
std::cout << "Connection not established..." << std::endl;
std::cout << "Trying to close socket..." << std::endl;
stop();
return;
}
}
Otherwise the implicit cancel of the timer after successful connect will still close() the socket :)
If you want to run (many) connection attempts in parallel, you don't need any more threads or even more than one io_service. This is the essence of Boost Asio: you can do asynchronous IO operations on a single thread.
This answer gives a pretty isolated picture of this (even though the connections are done using ZMQ there): boost asio deadline_timer async_wait(N seconds) twice within N seconds cause operation canceled
another example, this time about timing out many sessions independently on a single io_service: boost::asio::deadline_timer::async_wait not firing callback
I have small piece of code
boost::asio::ip::tcp::no_delay option(true);
boost::asio::ip::tcp::socket* sock = new boost::asio::ip::tcp::socket(ios);
sock->set_option(option);
_session_acceptor.async_accept(*sock,
boost::bind(&server::playerAccept, this, sock, boost::asio::placeholders::error));
If i call set_option on socket before accepting server dont accept any connections. But if i call set_option after connections are accepted. Is there any magic?
You should call set_option on acceptor, not socket. Example from my project:
Listener::Listener(int port)
: acceptor(io, ip::tcp::endpoint(ip::tcp::v4(), port))
, socket(io) {
boost::asio::ip::tcp::no_delay opt_nodelay(true);
acceptor.set_option(opt_nodelay);
start_accept();
try
{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
//how do i make a checker here if the client is not sending anything then server send or if the client sending then server recive
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
how do i make a checker, if the client is not sending anything then server send or if the client sending then server recive
The question is not immediately clear.
I would start an async_read() with an associated deadline_timer set to an appropriate value. If your timer expires before any reading was performed, then have your server send its data.
I use synchronous boost::asio SSL sockets in my application. I initialize all parameters and then connect to some hosts (one after another) and do a GET request for each host.
Everything works until I get a "404 - Not Found" error for one of the hosts. After this error, all new connections fail with some unspecified SSL error.
Do I have to reset the ssl::stream somehow? Is it possible to re-initialize the ssl::stream after each connection?
In the following code snippets I removed error handling and all non asio related things.
Main:
asio::io_service ioservice;
asio::ssl::context ctx(ioservice, asio::ssl::context::sslv23);
ctx.set_verify_mode(asio::ssl::context::verify_none);
Connector *con = new Connector(ioservice, ctx);
while (!iplist.empty())
{
...
con->ssl_connect(ipaddress, port);
...
}
Connector:
Connector::Connector(asio::io_service& io_service, asio::ssl::context &ctx)
: sslSock(io_service, ctx)
{
}
Connector::ssl_connect(std::string ipAdr, std::string port)
{
...
tcp::resolver resolver(ioserv);
tcp::resolver::query query(ipAdr, port);
endpoint_iterator = resolver.resolve(query);
...
asio::error_code errorcode = asio::error::host_not_found;
tcp::resolver::iterator end;
// Establish connection
while (errorcode && endpoint_iterator != end)
{
sslSock.lowest_layer().close();
sslSock.lowest_layer().connect(*endpoint_iterator++, errorcode);
}
sslSock.handshake(asio::ssl::stream_base::client, errorcode);
...
asio::write(...);
...
asio::read(...);
...
sslSock.lowest_layer().close();
...
return;
}
I got the answer from the asio mailing list (many thanks to Marsh Ray). Sam Miller was correct in that the asio::ssl::context has to be created each time. To achieve this, std::auto_ptr is used.
Connector.h:
std::auto_ptr<asio::ssl::stream<tcp::socket>> sslSock;
Connector.cpp:
asio::ssl::context ctx(ioserv, asio::ssl::context::sslv23);
ctx.set_verify_mode(asio::ssl::context::verify_none);
sslSock.reset(new asio::ssl::stream<tcp::socket>(ioserv, ctx));
you might try recreating the asio::ssl::context each time you create a asio::ssl::stream.
I saw the same exception because I ran curl_global_cleanup(); before I was done with curl in the application.