1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
class sockbuf : public std::streambuf {
protected:
SOCKET s;
static const int bufSize = 1024;
char buf[bufSize];
public:
explicit sockbuf(SOCKET sock) : s(sock) {
setg(buf+4, buf+4, buf+4);
}
protected:
virtual
int_type overflow(int_type c) {
if (c == EOF)
return EOF;
int rv = send(s, (char*)&c, 1, 0);
if (rv != 1)
return EOF;
return rv;
}
virtual
int_type underflow() {
if (gptr() < egptr())
return *gptr();
int numPutBack = std::min(4, gptr() - eback());
std::memcpy(buf+(4-numPutBack), gptr()-numPutBack, numPutBack);
int num = recv(s, buf+4, bufSize-4, 0);
if (num == SOCKET_ERROR || num == 0)
return EOF;
setg(buf+(4-numPutBack), buf+4, buf+4+num);
return *gptr();
}
virtual
std::streamsize xsputn(const char *buf, std::streamsize num) {
int rv = send(s, buf, num, 0);
if (rv == SOCKET_ERROR)
return EOF;
return rv;
}
};
|