Question

Greetings. I'm just getting started with the boost::asio library and have run into some early difficulty related to boost::asio::ip::tcp::iostream.

My question has two parts:

1.) How does one connect an iostream using simply host and port number?

I can make the client and server [boost.org] examples work fine as coded. The server specifies the port explicitly:

boost::asio::io_service io_service;

tcp::endpoint endpoint(tcp::v4(), 13);
tcp::acceptor acceptor(io_service, endpoint);

Port 13 is a well-known port for a "daytime" service.

The client example connects by specifying a host and the service name:

tcp::iostream s(argv[1], "daytime");

For my own application, I would like to put the server on an arbitrary port and connect by number as shown below:

Server:

boost::asio::io_service io_service;
tcp::endpoint endpoint(tcp::v4(), port);
tcp::acceptor acceptor(io_service, endpoint);
acceptor.accept(*this->socketStream.rdbuf());
...

Client:

boost::asio::ip::tcp::iostream sockStream;
...
sockStream.connect("localhost", port);
...

If, in the client, I try to specify the port number directly (instead of a service by name), the stream fails to connect. Is there a way to do this? It is not clear to me what the arguments to connect could/should be.


2.) What is the preferred way to test the success of a call to iostream::connect?

The function returns void, and no exception is thrown. The only method I've devised so far is to test the stream.fail() and/or stream.good(). Is this the way to do it, or is there some other method.


Advice on one or both of these would be appreciated. Also, if I am overlooking pertinent documentation and/or examples those would be nice. So far I haven't been able to answer these questions by reading the library docs or searching the 'net.

Was it helpful?

Solution

I don't know why asio doesn't work (at least with Boost 1.35.0) with a port number expressed as an int. But, you can specify the port number as a string. i.e.

tcp::iostream s(hostname, "13");

should work.

concerning error detection:

tcp::socket has a connect() method which takes and endpoint and a reference to a boost::system::error_code object which will tell you if it connected successfully.

OTHER TIPS

Even though no error is returned, stream.error() contains the latest error code. I used the code

do
{
    m_stream.clear();
    m_stream.connect(host, port);
}
while(m_stream.error());`

You could also only check for the specific error boost::asio::error::connection_refused.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top