001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 *
019 */
020package org.apache.mina.example.echoserver;
021
022import org.apache.mina.core.buffer.IoBuffer;
023import org.apache.mina.core.service.IoHandler;
024import org.apache.mina.core.service.IoHandlerAdapter;
025import org.apache.mina.core.session.IdleStatus;
026import org.apache.mina.core.session.IoSession;
027import org.apache.mina.filter.ssl.SslFilter;
028import org.slf4j.Logger;
029import org.slf4j.LoggerFactory;
030
031/**
032 * {@link IoHandler} implementation for echo server.
033 *
034 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
035 */
036public class EchoProtocolHandler extends IoHandlerAdapter {
037    private final static Logger LOGGER = LoggerFactory.getLogger(EchoProtocolHandler.class);
038    
039    @Override
040    public void sessionCreated(IoSession session) {
041        session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
042
043        // We're going to use SSL negotiation notification.
044        session.setAttribute(SslFilter.USE_NOTIFICATION);
045    }
046
047    @Override
048    public void sessionClosed(IoSession session) throws Exception {
049        LOGGER.info("CLOSED");
050    }
051
052    @Override
053    public void sessionOpened(IoSession session) throws Exception {
054        LOGGER.info("OPENED");
055    }
056
057    @Override
058    public void sessionIdle(IoSession session, IdleStatus status) {
059        LOGGER.info("*** IDLE #" + session.getIdleCount(IdleStatus.BOTH_IDLE) + " ***");
060    }
061
062    @Override
063    public void exceptionCaught(IoSession session, Throwable cause) {
064        session.closeNow();
065    }
066
067    @Override
068    public void messageReceived(IoSession session, Object message)
069            throws Exception {
070        LOGGER.info( "Received : " + message );
071        // Write the received data back to remote peer
072        session.write(((IoBuffer) message).duplicate());
073    }
074}