473,657 Members | 2,435 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inheriting streambuf

Hi!
I was planning to wrap a socket inside an iostream, to achieve
something like this:
TCPSocket s(..);
s << "Hello!" << endl;

Information on the web seems to be a bit scarce on how to do this.
I have understood that there is a relation between streambuf and
iostream, where one should be able to extend streambuf and override
the underflow/overflow functions (and do send()/recv() for example).
My concepts are a bit dim.

Here are my questions:
If I inherit streambuf, which functions do I have to override
to achieve buffered IO with arbitrary buffer size?

How do I create an iostream which uses my extended streambuf?

I appreciate all answers.

Viktor Lundström

Jul 19 '05 #1
3 12029
Viktor Lundström <d9*****@nada.k th.se> wrote in message news:<Pi******* *************** *************** @knatte.nada.kt h.se>...
I was planning to wrap a socket inside an iostream, to achieve
something like this:
TCPSocket s(..);
s << "Hello!" << endl;
(Note that sockets are off-topic in this newsgroup, but IOStreams are
dead-on, so I'll help where I can.)

"Socket streams" seem to be of limited use in real programs. Many of
them exist out there -- I've even written one or two -- but what seems
to be a good idea actually turns out to be disastrous.

C++ iostreams are designed to be used with consistent streams of data.
That is, each request for n bytes either retrieves exactly n bytes or
signals an error. There is no provision for a stream which routinely
return less than n bytes, yet that's how TCP operates. Furthermore,
you must account for the possibility that the other end of the socket
is evil or broken. At the very least, getting it right is difficult,
if not impossible. The only foolproof way seems to be to read a single
char at a time, but that (to me) defeats the purpose of using a
stream.

If you wish to continue, you might want to check out Kreft and
Langer's "IOStreams and Locales," a book all about IOStreams (and
locales).
Information on the web seems to be a bit scarce on how to do this.
That's funny, considering how many times it's been done. :) Off the
top of my head:

- Socket++ (http://www.cs.utexas.edu/users/laven...urses/socket++)
is very out of date and usually doesn't compile out of the box, but it
comes with sockbuf and iosockinet classes.

- ACE (http://www.cs.wustl.edu/~schmidt/ACE.html) is very robust,
enterprise caliber, and well supported. It's also bloody huge, but
quite portable. Its ACE_IOStream class is very out of date and in fact
is disabled in the build rules for modern C++ compilers.

- GNU Common C++ (http://www.gnu.org/software/commonc++/) was crap,
at least as of the 1.x release; I started with ACE about when 2.0 came
out. However, it has an ost::tcpstream class.

- Netxx (http://pmade.org/software/netxx/) has its Netxx::Netbuf
class template. I've never used it.
I have understood that there is a relation between streambuf and
iostream, where one should be able to extend streambuf and override
the underflow/overflow functions (and do send()/recv() for example).
My concepts are a bit dim.
I think the important ones are underflow, uflow, overflow, xsgetn,
xsputn, and sync. You can optionally support the locales and
user-defined buffer operations (or you can just use your own internal
buffer -- std::vector<cha r> or std::string, maybe).
Here are my questions:
If I inherit streambuf, which functions do I have to override
to achieve buffered IO with arbitrary buffer size?
All functions marked "virtual" can be overridden, and any decent C++
reference should give you a list of them. For instance:

<http://dinkumware.com/htm_cpl/streambu.html>

Read the docs, figure out what they do, and override the ones that
apply to your stream.
How do I create an iostream which uses my extended streambuf?


One way:

#include <iostream>

class SockBuf : public std::streambuf {
public:
bool connect (...);
// other socket-related functions here

private: // these are never called directly, so they're private
// override virtual member functions here
};

class SockStream : private SockBuf, public std::iostream {
public:
SockStream () : std::iostream(t his) { } // "this" as SockBuf *
SockStream (...) : SockBuf(...), std::iostream(t his) { }

using SockBuf::connec t;
// other socket-related using declarations here
};

You could technically make both of these into one class; I prefer to
split them up (the "do one thing and do it well" principle).

- Shane
Jul 19 '05 #2
On 24 Sep 2003 23:15:52 -0700, sb******@cs.uic .edu (Shane Beasley)
wrote:
"Socket streams" seem to be of limited use in real programs. Many of
them exist out there -- I've even written one or two -- but what seems
to be a good idea actually turns out to be disastrous.

C++ iostreams are designed to be used with consistent streams of data.
That is, each request for n bytes either retrieves exactly n bytes or
signals an error. There is no provision for a stream which routinely
return less than n bytes, yet that's how TCP operates. Furthermore,
you must account for the possibility that the other end of the socket
is evil or broken. At the very least, getting it right is difficult,
if not impossible. The only foolproof way seems to be to read a single
char at a time, but that (to me) defeats the purpose of using a
stream.


It's fine to use it with sockets as long as you're happy with blocking
IO. IOStreams isn't very good for non-blocking IO though, so
alternative solutions should be sought if that is required. However, I
find blocking IO in a separate thread is generally easiest...

Tom
Jul 19 '05 #3
Viktor Lundström <d9*****@nada.k th.se> wrote:
Information on the web seems to be a bit scarce on how to do this.
Is it? I'm sure that I have posted at least 10 different stream buffers
to newsgroups, at least 5 of whom were perfectly applicable to your
question (ie. showed the use of the appropriate member functions). Even
though some of this stuff is pretty old by now, it is still applicable.
If I inherit streambuf, which functions do I have to override
to achieve buffered IO with arbitrary buffer size?
The absolute minimum for buffered I/O are:

- 'underflow()' for reading
- 'overflow()' and 'sync()' for writing

To improve performance you might want to also override 'xsgetn()' and
'xsputn()' but I suspect that this is not necessary for a socket
communication: it makes sense when huge blocks of data can be processed
more efficiently than smaller blocks. I don't think this is the case
for sockets although it may be possible to avoid copying the bytes one
time.

What you have to do in your stream buffer for sockets is pretty simple:

- You have to create the socket itself, probably in the constructor or
even earlier from another class.
- You have to create input and output buffers. These are probably best
allocated in the constructor. Initialization of the stream buffer to
become aware of the get buffer is a natural thing to be done in
'underflow()'. Eg.:

int socketbuf::s_bu fsize const = 1024;
socketbuf::sock etbuf(int fd):
m_fd(fd), m_in(new char[s_bufsize]), m_out(new char[s_bufsize])
{
// set up the output buffer to leave at least one space empty:
setp(m_out, m_out + s_bufsize - 1);
}
socketbuf::~soc ketbuf() { delete[] m_in; delete[] m_out; }

- 'overflow()' is called when the buffer is full and a character is
attempted to be put into the buffer. In addition, it may be called
with an argument of 'traits_type::e of()', indicating that the buffer
should be flushed. Since there is a one character space left, the
passed character is put there and 'sync()' is called:

socketbuf::int_ type socketbuf::over flow(int_type c) {
if (!traits_type:: eq_int_type(tra its_type::eof() , c)) {
traits_type::as sign(*pptr(), traits_type::to _char_type(c));
pbump(1);
}
return sync() == 0? traits_type::no t_eof(c): traits_type::eo f();
}

- 'sync()' is called to bring the internal and the external stream
into synchronization . This effectively means that the output buffer
is to be flushed:

int socketbuf::sync () {
return pbase() == pptr() ||
write(m_fd, pbase(), pptr() - pbase()) == pptr() - base()? 0: 1;
}

- 'underflow()' is called when a character is to be read but none is
available. It is supposed to fill a buffer (if no buffer is used for
input, you need to implement 'uflow()', too). A real implementation
will move a few characters of the previous buffer to the front of
the new buffer to always allow put back (this is not done here for
brevity):

socketbuf::int_ type socketbuf::unde rflow() {
int rc = read(m_fd, m_in, s_bufsize);
if (rc <= 0)
return traits_type::eo f();
setg(m_in, m_in, m_in + rc);
return traits_type::to _int_type(*gptr ());
}

The sequence between the first parameter to 'setg()' and the second
parameter is the "put back area" (in this case empty): if you retain
characters for put back, you start reading beginning at the second
parameter.

That's it (... and all of this I have said before, although with
different words, in articles I have posted in the past).
How do I create an iostream which uses my extended streambuf?


The stream classes and 'std::ios' have a constructor taking a pointer
to 'std::streambuf '. So you can simply use these constructors to
create an appropriate stream, eg.:

socketbuf socketbuf(open_ socket_somehow( ));
std::istream socketin(&socke tbuf);

Typically, construction of the stream buffer is encapsulated into
a class derived from 'std::istream', 'std::ostream', or
'std::iostream' . I have shown this technique in several articles I
have posted in the past...
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
Phaidros eaSE - Easy Software Engineering: <http://www.phaidros.co m/>
Jul 19 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2179
by: Christopher Benson-Manica | last post by:
This is starting to seem ridiculous to me :( #include <streambuf> #include <iostream> class TWFileStream : public std::streambuf { private: char cbuf;
9
2703
by: Fred Ma | last post by:
Hello, I posted previously under the thread: How to break this up into streambuf/ostream I've asked our library to get "C++ IOStreams and Locales..." by A. Langer et al. Meantime, I've looked at the C++ standard (ISO/IEC 14882) from the web to get a grip on the relationship between ostream methods and streambuf methods: flush(), operator<<(), sputc(),
4
3049
by: Thomas Matthews | last post by:
Hi, My objective is to add enable & disable functionality to the ofstream class. I want to have a log file where I can disable and enable output to it. When my first tests pass, I want to disable the annotations written to the log file, but enable the text from the newer test cases. I've searched the C++ newsgroups and the FAQ-Lite
9
5754
by: Marcin Kalicinski | last post by:
Hi, I have a set of C-like functions for file access (like fopen, fwrite, fread, fseek etc.). But I want to access the files using C++ stream, not these functions. What I probably need to do is to create custom streambuf class (am I right?). Is there any free source code or tutorial available on how to do that? I have googled for it, but I only found partial and untested solutions. Worse, the solutions were pretty complicated,...
2
2762
by: Raf256 | last post by:
Hello, my custom streambuf works fine with output via << and with input via .get() but fails to input via >> or getline... any idea why? -------------------- A custom stream buffer (for encryption, currently it is doing "nothing")
7
7011
by: smith4894 | last post by:
Hello all, I'm working on writing my own streambuf classes (to use in my custom ostream/isteam classes that will handle reading/writing data to a mmap'd file). When reading from the mmap file, I essentially have a char buffer in my streambuf class, that I'm registering with setp(). on an overflow() call, I simply copy the contents of the buffer into the mmap'd file via memcpy().
4
6403
by: rakesh.usenet | last post by:
For a particular application of mine - I need a simulation of byte array output stream. * write data onto a stream * getback the contiguous content as an array later for network transport. My code looks as follows. #include <iostream>
1
3435
by: AJG | last post by:
Hi there. I am using a library called SOCI that has a method to set a stream which it uses to log SQL queries. The signature is as follows: void setLogStream(std::ostream *s); This works great when used with something like setLogStream(&std::cerr). However, I would like to add more context to the query logged. Specifically, I'd like to add the thread ID. So, instead of the query logged looking like:
3
4722
by: Raymond Martineau | last post by:
I have the following code segment for a class intended to split output between cout and a file: class SplitStream : public std::streambuf { std::streambuf *x; public: SplitStream() {
0
8395
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8310
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7330
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6166
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.