?
?
mina 的一个简单例子 ? ?时间服务器,实现最基本功能
?
?
package server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.example.gettingstarted.timeserver.TimeServerHandler; 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 MinaTimeServer { private static final int PORT=6489; 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 TimeServerHandler()); acceptor.getSessionConfig().setReadBufferSize(2048); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); acceptor.bind(new InetSocketAddress(PORT)); System.out.println("service start"); } }?
?
?
?
?
package server; import java.sql.Date; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; public class TimeServerHandler implements IoHandler { public void exceptionCaught(IoSession session, Throwable cause) throws Exception { // TODO Auto-generated method stub cause.printStackTrace(); } public void messageReceived(IoSession session, Object message) throws Exception { // TODO Auto-generated method stub String strMsg= message.toString(); if(strMsg.trim().equalsIgnoreCase("quit")){ session.close(); return; } Date date = new Date(0); session.write(date.toString()); System.out.println("message writen..."); } public void messageSent(IoSession arg0, Object arg1) throws Exception { // TODO Auto-generated method stub } public void sessionClosed(IoSession arg0) throws Exception { // TODO Auto-generated method stub } public void sessionCreated(IoSession arg0) throws Exception { // TODO Auto-generated method stub } public void sessionIdle(IoSession session, IdleStatus status) throws Exception { System.out.println("IDLE"+session.getIdleCount(status)); } public void sessionOpened(IoSession arg0) throws Exception { // TODO Auto-generated method stub } }?
?