(一)
package client; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.NioSocketConnector; public class MinaSimpleClient { private static String HOSTNAME = "localhost"; private static int PORT = 9123; public static void main(String[] args) throws InterruptedException { NioSocketConnector connector = new NioSocketConnector(); // 设置编码解码器 connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); // 设置Handler connector.setHandler(new ClientTimerHandler()); // 获取连接,该方法为异步执行 ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT)); // 设置空闲时间 connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); // 等待连接建立 future.awaitUninterruptibly(); // 获取session IoSession session = future.getSession(); // 等待session关闭 session.getCloseFuture().awaitUninterruptibly(); // 释放connector资源 // 实际开发中,不要频繁关闭connector,因为它是重量级资源,应该设计成单例或者连接池 connector.dispose(); } }
(二)
package client; import java.sql.Timestamp; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; public class ClientTimerHandler extends IoHandlerAdapter { // 当一个客户端连接到服务器之后 // 当打开一个连接时被触发。在目前的实现中,好像 sessionOpened 和 sessionCreated 没有太大区别, @Override public void sessionOpened(IoSession session) throws Exception { System.out.println("连接到服务器"); } // 当消息创建时 @Override public void sessionCreated(IoSession session) throws Exception { // session 创建时调用 session.write("消息创建"); System.out.println("消息创建"); } // 消息到达时 @Override public void messageReceived(IoSession session, Object message) throws Exception { // 异步接收消息 String str = message.toString(); System.out.println("接收服务端消息:" + str); } // 异常时调用 @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { // 出现异常 System.out.println("服务器端断了!"); cause.printStackTrace(); session.close(true); } // 消息空闲时 @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { System.out.println("[Time]:" + new Timestamp(System.currentTimeMillis()) + "连接空闲"); if (session != null) { session.close(); System.out.println("空闲时间过后,session被关闭"); } } // 当一个客户端关闭时 @Override public void sessionClosed(IoSession session) { System.out.println("I'm Client =" + session.getId() + " I closed!"); } }