On Tue, Sep 4, 2012 at 2:34 PM, Bernhard Brodowsky <[email protected]> wrote:
> Hi, I am implementing a special kind of socket that takes an io object
> (usually a socket) as its argument and then behaves like a socket, but
> does some transformations before/after it sends/receives, so in pseudo
> code, it could look about like this:

> But now I would like to implement the io interface like all those other
> io classes,

Why?  I'd rather have a clean separation, i.e. you have a class
representing the connection on a higher level of abstraction and make
it contain a Socket instance.  Then implement the methods you need on
the abstract level.  You could also have custom classes for messages
(or only one custom class depending on your needs).  That way you make
sure clients pass in only what they are allowed to etc.

If you allow the socket to be visible outside your connection class
you allow people to manipulate the socket in arbitrary ways which
might interfere with your message exchange logic.  It's usually better
to have this layered approach and manipulations of the socket which
interfere with your logic (i.e. for example, someone invoking
close_read() while you are still waiting for an answer).

> Since the length of the messages I send through the internal sockets are
> fixed (because of the kind of transformations I do), I should probably
> use an internal buffer and for example return the next byte of that
> buffer if getc is called and if the buffer is empty, receive the next
> message and put it into the buffer. But what should I use for the
> buffer? I could use a string, but I guess +=ing and splitting strings
> all the time may not be the most efficient way to do it.

You can use String#<< and String#slice! which are more efficient.
But: since the length is fixed I'd probably just have a thread reading
messages which simply uses @socket.read(1234).  That will block until
a message is complete.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- You received this message because you are subscribed to the Google Groups 
ruby-talk-google group. To post to this group, send email to 
[email protected]. To unsubscribe from this group, send email 
to [email protected]. For more options, visit this 
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en

Reply via email to