日期:2014-05-17 浏览次数:20903 次
package aicu.mina; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.SimpleByteBufferAllocator; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; public class MinaTimeServer { private static final int PORT = 9123; public static void main(String[] args) throws IOException { //设置buffer ByteBuffer.setUseDirectBuffers(false); ByteBuffer.setAllocator(new SimpleByteBufferAllocator()); //定义acceptor IoAcceptor acceptor = new SocketAcceptor(); //定义config SocketAcceptorConfig cfg = new SocketAcceptorConfig(); //设置config,加入filter cfg.getSessionConfig().setReuseAddress( true ); cfg.getFilterChain().addLast( "logger", new LoggingFilter() ); cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" )))); //加入port handler cfg acceptor.bind( new InetSocketAddress(PORT), new TimeServerHandler(), cfg); System.out.println("MINA Time server started."); } }
package aicu.mina; import java.util.Date; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.common.TransportType; import org.apache.mina.transport.socket.nio.SocketSessionConfig; public class TimeServerHandler extends IoHandlerAdapter { public void exceptionCaught(IoSession session, Throwable t) throws Exception { t.printStackTrace(); session.close(); } public void messageReceived(IoSession session, Object msg) throws Exception { String str = msg.toString(); //如果是quit就关闭session退出 if( str.trim().equalsIgnoreCase("quit") ) { session.close(); return; } //否则打印当前日期 Date date = new Date(); session.write( date.toString() ); System.out.println("Message written"); } public void sessionCreated(IoSession session) throws Exception { System.out.println("Session created"); if( session.getTransportType() == TransportType.SOCKET ) ((SocketSessionConfig) session.getConfig() ).setReceiveBufferSize( 2048 ); session.setIdleTime( IdleStatus.BOTH_IDLE, 10 ); } }