一個簡單的例子,對Mina架構有了大體的瞭解,在上節的基礎上,看看 怎樣實現用戶端與服務端的通訊,
廢話不多說了,直接看代碼:
public class Test { public static void main(String[] args) throws Exception{ SocketConnector connector = new NioSocketConnector(); IoFilter filter = new ProtocolCodecFilter(new TextLineCodecFactory()); connector.getFilterChain().addLast("vestigge", filter); SocketAddress soketAddress = new InetSocketAddress("127.0.0.1", 5469); connector.setHandler(new ClientHandler()); ConnectFuture future= connector.connect(soketAddress); future.join(); if (!future.isConnected()) { System.out.println("串連伺服器失敗"); return; } future.getSession().write("hello"); } }
可以看到代碼與伺服器端的代碼很像,也是非常的簡單,這就是架構的好處,不用再重複發明輪子,省了不少事,
public class ClientHandler extends IoHandlerAdapter { public void messageReceived(IoSession arg0, Object message) throws Exception { System.out.println("收到伺服器訊息:" + message.toString()); } public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception { } }
效果示範: