日期:2014-05-17 浏览次数:20992 次
package net.javasight.mina; /** * @author javasight */ import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; public class MinaServer { private static final int PORT = 1234; public static void main(String[] args) throws IOException { IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast("logger", new LoggingFilter()); acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset .forName("UTF-8")))); acceptor.setHandler(new MinaServerHandler()); acceptor.getSessionConfig().setReadBufferSize(2048); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); acceptor.bind(new InetSocketAddress(PORT)); } }
package net.javasight.mina; import org.apache.log4j.Logger; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; /** * @author javasight */ public class MinaServerHandler extends IoHandlerAdapter { private final Logger logger = Logger.getLogger(getClass()); @Override public void sessionOpened(IoSession session) { // set idle time to 10 seconds session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); session.setAttribute("Values: "); } @Override public void messageReceived(IoSession session, Object message) { logger.info("Message received in the server.."); logger.info("Message is: " + message.toString()); } @Override public void sessionIdle(IoSession session, IdleStatus status) { logger.info("Disconnecting the idle."); // disconnect an idle client session.close(); } @Override public void exceptionCaught(IoSession session, Throwable cause) { // close the connection on exceptional situation session.close(); } }