mina第一篇:基本demo實現
阿新 • • 發佈:2019-01-30
今天看了下mina,實現了最簡單的功能,其實就是一個傳輸字串,但是受益匪淺.
廢話少說,先介紹步驟
1、準備好幾個包
log4j.jar
mina-core-2.0.4.jar
slf4j-api-1.6.3.jar
slf4j-log4j12-1.6.3.jar
2、自行建立幾個類
首先是客戶端
/** * mina客戶端 * @author aniyo * blog:http://aniyo.iteye.com */ public class MinaClient { public static void main(String []args)throws Exception{ //Create TCP/IP connection NioSocketConnector connector = new NioSocketConnector(); //建立接受資料的過濾器 DefaultIoFilterChainBuilder chain = connector.getFilterChain(); //設定這個過濾器將一行一行(/r/n)的讀取資料 chain.addLast("myChin", new ProtocolCodecFilter(new TextLineCodecFactory())); //客戶端的訊息處理器:一個SamplMinaServerHander物件 connector.setHandler(new MinaClientHandler()); //set connect timeout connector.setConnectTimeout(5000); //連線到伺服器: ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",8080)); // Wait for the connection attempt to be finished. cf.awaitUninterruptibly(); cf.getSession().getCloseFuture().awaitUninterruptibly(); connector.dispose(); } }
/** * 客戶端業務處理邏輯 * * @author aniyo blog: http://aniyo.iteye.com */ public class MinaClientHandler extends IoHandlerAdapter { // 當客戶端連線進入時 @Override public void sessionOpened(IoSession session) throws Exception { System.out.println("incomming 客戶端: " + session.getRemoteAddress()); session.write("i am coming"); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { System.out.println("客戶端傳送資訊異常...."); } // 當客戶端傳送訊息到達時 @Override public void messageReceived(IoSession session, Object message) throws Exception { System.out.println("伺服器返回的資料:" + message.toString()); } @Override public void sessionClosed(IoSession session) throws Exception { System.out.println("客戶端與服務端斷開連線....."); } @Override public void sessionCreated(IoSession session) throws Exception { // TODO Auto-generated method stub System.out .println("one Client Connection" + session.getRemoteAddress()); session.write("我來了······"); } }
然後是服務端
/** * @author aniyo * blog: http://aniyo.iteye.com */ public class MinaTimeServer { // 伺服器監聽埠 private static final int PORT = 8080; /** * */ public MinaTimeServer() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // 伺服器端的主要物件 IoAcceptor acceptor = new NioSocketAcceptor(); // 設定Filter鏈 acceptor.getFilterChain().addLast("logger", new LoggingFilter()); // 協議解析,採用mina現成的UTF-8字串處理方式 acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); // 設定訊息處理類(建立、關閉Session,可讀可寫等等,繼承自介面IoHandler) acceptor.setHandler(new TimeServerHandler() ); // 設定接收快取區大小 acceptor.getSessionConfig().setReadBufferSize(2048); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); //讀寫通道無任何操作就進入空閒狀態 try { // 伺服器開始監聽 acceptor.bind( new InetSocketAddress(PORT) ); }catch(Exception e){ e.printStackTrace(); } } }
public class TimeServerHandler extends IoHandlerAdapter {
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}
/*
* 這個方法是目前這個類裡最主要的,
* 當接收到訊息,只要不是quit,就把伺服器當前的時間返回給客戶端
* 如果是quit,則關閉客戶端連線*/
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
String str = message.toString();
if (str.trim().equalsIgnoreCase("quit")) {
session.close();
return;
}
Date date = new Date();
System.out.println("hello"+str+session.getRemoteAddress()+date.toString());
session.write("iamrecived");
System.out.println("Message written...");
}
@Override
public void sessionClosed(IoSession session) throws Exception {
// TODO Auto-generated method stub
super.sessionClosed(session);
System.out.println("客戶端與服務端斷開連線.....");
}
}
操作步驟
1、執行服務端(MinaTimeServer)
2、訪問127.0.0.1:8080 自己的埠
3、訪問客戶端
領悟:服務端開啟監聽, 客戶端進行連線,每次連線都會傳輸,服務端實現IoAcceptor介面, 客戶端實現IOconnector介面.
程式碼下載
http://download.csdn.net/detail/u010310183/9560573