3

I'd like to inherit std::basic_streambuf to implement a stream buffer based on a TCP connection. I don't understand exactly the role of the pointers eback, gptr, egptr, pbase, pptr, epptr. I was thinking of a stream buffer as an entity that simply lets u read characters from or write characters to a stream, and possibly to reposition the read/write pointers (not in my case). These pointers don't make sense for me, as I was thinking to implement a circular buffer for the input and output (so it's possible that, e.g., gend < gbeg). Do I really have to implement those pointers (eback, gptr, etc...), or I can just set them all to nullptr and everything will work fine? Or there is some function that would use them?

Yaron Cohen-Tal
  • 2,005
  • 1
  • 15
  • 26
  • There is some code here that you can examine (or just use) [fdstream](http://www.josuttis.com/cppcode/fdstream.html). You can give the `fdstream` a socket file descriptor. Alternatively `GCC` has `stdio_filebuf` as a library extension `#include `. Again just pass it a socket file descriptor. – Galik May 17 '15 at 09:25

1 Answers1

4

(First off, it's great to see the decision to make a TCP streambuf rather than a TCP stream.)

Angelika Langer & Klaus Kleft have very good stuff on this, besides the book, here is a whole section of tutorials.

However, streambufs often involve lots of boilerplate code, and, therefore, for an actual problem such as yours, I'd use boost::iostreams, in particular source (for a source tcp stream; obviously use target for the other way).

Note how this class has abstracted away the lower level ops you mentioned. You basically need to implement

std::streamsize read(char* s, std::streamsize n);

and it will take care of the rest for you (without much overhead).

As for your (reasonable sounding) idea to use a circular buffer, you might use boost::circular_buffer. Alternatively, see this question.

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • Thanx, @Ami. I'm not sure though I wanna use Boost as my program should be cross-platform (including Android), and it seems like Boost doesn't officially support Android. – Yaron Cohen-Tal May 23 '15 at 15:26
  • Then I suggest Langer & Kleft, esp. [here](http://www.angelikalanger.com/IOStreams/Excerpt/excerpt.htm) if you don't have the book. – Ami Tavory May 23 '15 at 16:39