Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an 'ostream' from a socket?

Tags:

c++

sockets

In C++, if I have a socket, how can I create an ostream object from it?

I have googled some example: http://members.aon.at/hstraub/linux/socket++/docu/socket++_10.html

And I have tried:

 sockbuf sb(sockfd);
 std::ostream outputStream(&sb);

But I can't find the .h file and the library to link with for 'sockbuf'. Is that part of a standard c++ library?

like image 647
silverburgh Avatar asked Feb 05 '10 01:02

silverburgh


3 Answers

The site you found is a third party non-standard library. There is no standard C++ socket library.

However, if you want as closest to a standard (and powerful!) solution, you should try Boost.Asio. It has been proposed for inclusion in the standard library (TR2). Here's an iostream based example:

boost::asio::ip::tcp::iostream stream("www.example.org", "http");
stream << "GET / HTTP/1.0\r\nHost: www.boost.org\r\n\r\n" << std::flush;

std::string response;
std::getline( stream, response );

However, you'd gain much more if using the Asio's Proactor for asynchronous operation.

like image 148
Kornel Kisielewicz Avatar answered Nov 20 '22 06:11

Kornel Kisielewicz


Standard C++ (at least C++98) does not deal with networking in any way. So, you have to do something platform-specific.

Some platforms have IOStreams implementations that allow you to create a stream from a file descriptor. In that case, use the socket descriptor as your file descriptor.

like image 6
Chris Jester-Young Avatar answered Nov 20 '22 06:11

Chris Jester-Young


It is not part of the standard C++ library. Download Socket++ here: http://members.aon.at/hstraub/linux/socket++/ (it was a few directories back from what you pasted)

like image 1
Chris Dennett Avatar answered Nov 20 '22 08:11

Chris Dennett