最近因爲工做內容比較空閒,加上對於Java網絡框架方面知識的欠缺,決定深刻學習NIO框架Mina及Netty;如下是Mina框架最簡單的HelloWorld Demo。windows
MinaServer:
public class MinaServer { public static void main(String[] args){ try { //建立一個IoAcceptor實例 NioSocketAcceptor acceptor = new NioSocketAcceptor(); //添加解碼器 acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory())); //添加日誌 acceptor.getFilterChain().addLast("logger", new LoggingFilter()); //指定IoHandler acceptor.setHandler(new MinaServerAdapter()); //綁定端口 acceptor.bind(new InetSocketAddress(Constants.PORT)); } catch (IOException e) { e.printStackTrace(); } } }
MinaServerAdapter
public class MinaServerAdapter extends IoHandlerAdapter { //sessionCreated:建立時回調 @Override public void sessionCreated(IoSession session) throws Exception { System.out.println("sessionCreated"); } //sessionOpened:打開時回調 @Override public void sessionOpened(IoSession session) throws Exception { System.out.println("sessionOpened"); } //sessionClosed:關閉時回調 @Override public void sessionClosed(IoSession session) throws Exception { System.out.println("sessionClosed"); } //sessionIdle:進入空閒時回調 @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { System.out.println("sessionIdle"); } //出現異常時回調 @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { cause.printStackTrace(); System.out.println("exceptionCaught:"+cause.getMessage()); } /** * 接收到消息時回調 */ @Override public void messageReceived(IoSession session, Object message) throws Exception { String str = message.toString(); System.out.println("Received Message is: " + str); if("exit".equals(str)){ System.out.println("client exit: " + str); session.write("client exit"); session.closeNow(); return; } Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); session.write(format.format(date)+" Received Client Message : "+message); } @Override public void messageSent(IoSession session, Object message) throws Exception { System.out.println("messageSent"); } }
此時運行MinaServer的main方法,便可啓動Mina服務端。在windows系統下啓動CMD/Unix系統下啓動終端,輸入telnet IP PORT連接到Mina服務端,並可向Mina服務端發送消息。網絡
當Mina服務端收到exit字符串時,回話結束。session