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.gettingstarted.timeserver; 021 022import java.util.Date; 023 024import org.apache.mina.core.service.IoHandlerAdapter; 025import org.apache.mina.core.session.IdleStatus; 026import org.apache.mina.core.session.IoSession; 027 028/** 029 * The Time Server handler : it return the current date when a message is received, 030 * or close the session if the "quit" message is received. 031 * 032 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 033 */ 034public class TimeServerHandler extends IoHandlerAdapter 035{ 036 /** 037 * Trap exceptions. 038 */ 039 @Override 040 public void exceptionCaught( IoSession session, Throwable cause ) throws Exception 041 { 042 cause.printStackTrace(); 043 } 044 045 /** 046 * If the message is 'quit', we exit by closing the session. Otherwise, 047 * we return the current date. 048 */ 049 @Override 050 public void messageReceived( IoSession session, Object message ) throws Exception 051 { 052 String str = message.toString(); 053 054 if( str.trim().equalsIgnoreCase("quit") ) { 055 // "Quit" ? let's get out ... 056 session.close(true); 057 return; 058 } 059 060 // Send the current date back to the client 061 Date date = new Date(); 062 session.write( date.toString() ); 063 System.out.println("Message written..."); 064 } 065 066 /** 067 * On idle, we just write a message on the console 068 */ 069 @Override 070 public void sessionIdle( IoSession session, IdleStatus status ) throws Exception 071 { 072 System.out.println( "IDLE " + session.getIdleCount( status )); 073 } 074}