Paul Lammertsma
Paul Lammertsma

Reputation: 38292

Using Boost ASIO to process TCP without sockets

After following the tutorial on creating a combined TCP/UDP asynchronous server, I'm looking further into applying Boost ASIO to parse data directly from a byte stream.

My objective here is to provide some mechanism independent of sockets. In my scenario, I'm dealing with a file descriptor coming from a Java implementation. In Java, I can read the file descriptor using:

is = new FileInputStream(fd);
os = new FileOutputStream(fd);

Is it possible to replace sockets with some sort of input and output byte stream and have ASIO take care of processing TCP connections?

Something that came to mind was using connect from socket.h; something akin to:

connect((int) fd, (struct sockaddr *) &peerAddr, sizeof(peerAddr))

This of course sets up a connection and expects a peer sockaddr_in to connect to. I was hopeful that there might be some similar way of binding a boost::asio::ip::tcp::socket to a file descriptor. Is something of this nature possible?

Upvotes: 3

Views: 1058

Answers (2)

Traphicone
Traphicone

Reputation: 101

Though the Boost Asio documentation contains what you are looking for, it is hard to find (or even decipher) if you do not already know it is there.

Assuming you have an IPv4 TCP socket file descriptor fd from connect(2) or accept(2), you can wrap a Boost iostream around it with the following:

boost::asio::ip::tcp::iostream stream;
stream.rdbuf()->assign(boost::asio::ip::tcp::v4(), dup(fd));

Note the duplicated file descriptor, which prevents Boost from helpfully closing your native socket connection out from under you when your stream goes out of scope.

You will probably also want to adjust the backing buffer to fit your needs, as well:

char buf[1024]; // or whatever
stream.rdbuf()->pubsetbuf(buf, sizeof(buf));

Upvotes: 2

Nim
Nim

Reputation: 33655

Moving the comment to an answer, yes boost asio has a facility like this, it's called Socket IOStreams, see here: http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/overview/networking/iostreams.html

Upvotes: 2

Related Questions