开发者

Apache Mina , create my own IoSession: How to?

开发者 https://www.devze.com 2023-03-26 03:07 出处:网络
I\'m playing for a few days with apache mina and I want to ask you how can I create by extending (or implementing) IoSession to create something like MyIoSession.

I'm playing for a few days with apache mina and I want to ask you how can I create by extending (or implementing) IoSession to create something like MyIoSession.

The reason why I want to do this is because in the Handler class I want something like this:

public class MyHandler extends IoHandlerAdapter{
    public void messageReceived( MyIoSession session, Object message ) throws Exception
    {
        // here开发者_高级运维 I have MyIoSession instead of IoSession which will have more info something
        // like an unique ID
    }
}

This way MyIoSession will have some unique ID and this way I'll identify which client is sending messages to server.

Also if there are other better ways to achieve this feel free to tell me.

Thanks


I had a similar problem where I wanted to store specific information in the IoSession, just like you want with the unique ID. Since I didn't find out how to properly extend this whole mess (I was looking for a place where I could pass something like an IoSessionFactory in order to have MINA create my own IoSession implementation), I used the setAttribute(Object, Object) method to store information about this session. You could do it like this:

public class MyHandler extends IoHandlerAdapter{
    private enum AttributeKeys {
        KEY_UNIQUEID;
    }
    public void sessionCreated(IoSession session) throws Exception {
        //create and remember a uniqueID upon session creation
        session.setAttribute(AttributeKeys.KEY_UNIQUEID, createUniqueID());
    }

    //called with the regular IoSession
    public void messageReceived(IoSession session, Object message) throws Exception {
        //wherever you need the UniqueID, use getSessionUniqueID(session);
    }

    public String getSessionUniqueID(session){
       return session.getAttribute(AttributeKeys.KEY_UNIQUEID).toString();
    }
}

I would prefer a subclassing-solution as well, but I just went with this. Hope this helps in any way, other solutions would be welcome.

0

精彩评论

暂无评论...
验证码 换一张
取 消