ProtocolCodec discussion has been edited by Emmanuel Lécharny (Nov 11, 2008).

Change summary:

Created the page. Added some description for the sessionCreated event

(View changes)

Content:

Introduction

This filter is one of the most important one. In many case, writing a MINA based application without having such a filter added is not really meaningful.

Events handled

Here is a list of all the handled events in this filter :

event Handled Description
exceptionCaught N/A
filterClose N/A
filterSetTrafficMask Will be removed
filterWrite  
onPostRemove
onPreAdd
sessionOpened Useless. May be removed
messageReceived
messageSent
sessionClosed
sessionCreated
sessionIdle N/A

Description

Constructor

In order to be able to encode or decode a message, we need to pass the filter a factory, which will be used to create those two parts of the codec :

  • an encoder
  • a decoder

The factory is pretty simple. It offers two methods :

public interface ProtocolCodecFactory {
    /**
     * Returns a new (or reusable) instance of [EMAIL PROTECTED] ProtocolEncoder} which
     * encodes message objects into binary or protocol-specific data.
     */
    ProtocolEncoder getEncoder(IoSession session) throws Exception;

    /**
     * Returns a new (or reusable) instance of [EMAIL PROTECTED] ProtocolDecoder} which
     * decodes binary or protocol-specific data into message objects.
     */
    ProtocolDecoder getDecoder(IoSession session) throws Exception;
}

We can see that those two methods have a single parameter, an IoSession, which is a bad idea. A codec should not depend on a session. In fact, not a single codec uses this session, and I think that it should be removed.

Moreover, it forces the encoded and decoder instances to be created only when the first message is received, which can be a hassle, as ithe encoder/decoder creation has to be synchronized. It would be way better to create those instances when the filter is created.

It's also possible to pass the encoder and decoder directly, as a factory will be created internally to encapsulate those two methods.

SessionCreated event

The current handling for this event is pretty simple : it stores the Encoder and Decoder instances in the session attributes.

public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
        // Creates the decoder and stores it into the newly created session 
        session.setAttribute(DECODER, factory.getDecoder(session));

        // Creates the encoder and stores it into the newly created session 
        session.setAttribute(ENCODER, factory.getEncoder(session));

        // Call the next filter
        nextFilter.sessionCreated(session);
    }

The encoder and decoder are stateless, we don't need to pass a session object to the getEncoder/Decoder() methods.

SessionClosed event

Reply via email to