Saturday, November 6, 2010

Creating a std::iostream socket class (Part 1)

In the course of a project I'm currently working on, I've run across the need for some networking. In the past I've just wrapped up some Berkley sockets in a class and been done with it, but with this project I'm aiming to do things 'properly', using some of the more advanced features of C++ (including finally bidding a fond adieu to printf(), and starting to use std::cin / std::cout. After a bit of thought, I hit it. What better way to wrap up a socket than in a std::streambuf?

First port of call was trusty old cplusplus.com. Hmm. Nope, the same "you don't DESERVE to understand this" style as the standard library itself. Blargh. After some googling around, C++ Annotations 6.2.3 to the rescue! Now we're getting somewhere. Aha! Dr. Dobbs adds some insight.

Encouraged by the fact that it seemed possible, I looked around for existing libraries. A few options presented themselves in this excellent forum post, but they were all either too heavyweight or too awkward. Also, I just wanted to do it myself. Here's a snippet showing how simple it is to use:

std::string line;
tcpstream sock;
sock.connect("www.google.com", 80);
if (sock.bad()) handleError();
sock << "GET / HTTP/1.0\r\nConnection: close\r\n\r\n";
while (sock.connected()) {
std::getline(sock, line);
cout << line;
}

Next time I'll detail the process for creating a custom std::streambuf.

No comments:

Post a Comment