views:

1537

answers:

1

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.

+3  A: 

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.

Ferruccio
Thanks for the help. Is there then a way to take a tcp::socket and stuff it inside a tcp::iostream?
Adam
@Adam - I don't know. It's been awhile since I worked with asio and the code I'm looking at uses the socket directly for I/O (using socket::send and socket::read_some) rather than using an iostream.
Ferruccio
A slightly cleaner alternative is,sockStream.connect("localhost", lexical_cast<string>(port));
imran.fanaswala
@Adam - if you're trying to set boost::asio::socket_base options on a tcp::iostream, this can be done via rdbuf()->set_option() - see http://permalink.gmane.org/gmane.comp.lib.boost.asio.user/3961
therefromhere