I know, I just provided an example.
Here's a socket class I just wrote which derives from iostream. I works fine under windows at least.
Code:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <winsock.h>
class MyStreamBuf : public std::streambuf {
public:
MyStreamBuf(SOCKET* socket)
: s(socket)
{
setg(buf, buf+1, buf+1);
}
protected:
virtual int underflow()
{
setg(buf, buf, buf+1);
if (recv(*s, buf, 1, 0) != 1)
return EOF;
return buf[0];
}
virtual int overflow (int c = EOF)
{
char buf[1];
buf[0] = c;
send(*s, buf, 1, 0);
return c;
}
private:
SOCKET* s;
char buf[1];
};
class socketstream:
public std::iostream
{
protected:
MyStreamBuf strBuf;
SOCKET s;
bool open;
public:
socketstream(std::string address, int port)
: strBuf(&s),
std::iostream( &strBuf )
{
s = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in remoteAddr;
remoteAddr.sin_family = AF_INET;
remoteAddr.sin_addr.s_addr = inet_addr( address.c_str() );
remoteAddr.sin_port = htons( port );
memset (&remoteAddr.sin_zero,0, sizeof(remoteAddr.sin_zero));
open = connect(s, (sockaddr*)&remoteAddr, sizeof(remoteAddr)) != -1;
}
bool isOpen()
{
return open;
}
void closeConnection()
{
closesocket(s);
}
};
int main()
{
using namespace std;
WSADATA data;
WSAStartup(2,&data);
//Create a custom ostream object with our own
//stream buffer
socketstream sock("213.67.169.210", 80);
if (!sock.isOpen())
return 1;
sock << "GET / HTTP/1.1\n\n";
std::string s;
while (!sock.eof())
{
getline( sock, s );
cout << s;
}
cout << "\n\n\nConnection closed.";
cin.get();
}
It connects to my webserver and issues a GET command and prints whatever it recieves. It seems to work but as I've never programmed sockets in C++ and this was made rather hasty I've probably made a few errors in the socket programming.
But the principle works. I might extend it, as I've thought about creating this kind of class for some time. Only I haven't been able to derive from iostream until now.