How can I create an 'ostream' from a socke

2020-08-10 07:58发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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)



标签: c++ sockets