View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.example.echoserver;
21  
22  import org.apache.mina.core.buffer.IoBuffer;
23  import org.apache.mina.core.future.WriteFuture;
24  import org.apache.mina.core.service.IoHandler;
25  import org.apache.mina.core.service.IoHandlerAdapter;
26  import org.apache.mina.core.session.IdleStatus;
27  import org.apache.mina.core.session.IoSession;
28  import org.apache.mina.core.write.WriteRequest;
29  import org.apache.mina.filter.ssl.SslFilter;
30  import org.slf4j.Logger;
31  import org.slf4j.LoggerFactory;
32  
33  /**
34   * {@link IoHandler} implementation for echo server.
35   *
36   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
37   */
38  public class EchoProtocolHandler extends IoHandlerAdapter {
39      private final static Logger LOGGER = LoggerFactory.getLogger(EchoProtocolHandler.class);
40      
41      @Override
42      public void sessionCreated(IoSession session) {
43          session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
44  
45          // We're going to use SSL negotiation notification.
46          session.setAttribute(SslFilter.USE_NOTIFICATION);
47      }
48  
49      @Override
50      public void sessionClosed(IoSession session) throws Exception {
51          LOGGER.info("CLOSED");
52      }
53  
54      @Override
55      public void sessionOpened(IoSession session) throws Exception {
56          LOGGER.info("OPENED");
57      }
58  
59      @Override
60      public void sessionIdle(IoSession session, IdleStatus status) {
61          LOGGER.info("*** IDLE #" + session.getIdleCount(IdleStatus.BOTH_IDLE) + " ***");
62      }
63  
64      @Override
65      public void exceptionCaught(IoSession session, Throwable cause) {
66          session.close(true);
67      }
68  
69      @Override
70      public void messageReceived(IoSession session, Object message)
71              throws Exception {
72          LOGGER.info( "Received : " + message );
73          // Write the received data back to remote peer
74          session.write(((IoBuffer) message).duplicate());
75      }
76  }