标签:
IoConnector
一、断线重连的方式;
1. 在创建Mina客户端时增加一个监听器,或者增加一个拦截器,当检测到Session关闭时,自动进行重连。
2. 在第1种方式的基础上,增加客户端的读写通道空闲检查,当发生Session关闭或者读写空闲时,进行重连。
package com.yitop.feng.service; import org.apache.mina.core.filterchain.IoFilterAdapter; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.service.IoService; import org.apache.mina.core.service.IoServiceListener; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.core.session.IoSessionConfig; 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.SocketSessionConfig; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import java.nio.charset.Charset; /** * @author fengzp * @date 16/8/23 * @email fengzp@gzyitop.com * @company 广州易站通计算机科技有限公司 */ public class MinaClient { private static final Logger LOGGER = LoggerFactory.getLogger(MinaClient.class); private NioSocketConnector connector; private IoSession session; private String hostname = "127.0.0.1"; private int port = 8899; public MinaClient(){ init(); } private void init(){ connector = new NioSocketConnector(); connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"), "]", "]"))); /** * 一、使用监听器或拦截器实现断线重连 * 二、在第1种方式的基础上,增加客户端的读写通道空闲检查,当发生Session关闭或者读写空闲时,进行重连 */ //使用拦截器实现断线重连 connector.getFilterChain().addFirst("reconnection", new IoFilterAdapter(){ @Override public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { reconnect(); } }); //使用监听器实现断线重连 connector.addListener(new MyIoServiceListener()); connector.getSessionConfig().setReceiveBufferSize(10240); // 设置接收缓冲区的大小 connector.getSessionConfig().setSendBufferSize(10240);// 设置输出缓冲区的大小 connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30000); //读写都空闲时间:30秒 connector.getSessionConfig().setIdleTime(IdleStatus.READER_IDLE, 40000);//读(接收通道)空闲时间:40秒 connector.getSessionConfig().setIdleTime(IdleStatus.WRITER_IDLE, 50000);//写(发送通道)空闲时间:50秒 //在数据处理器IoHandler中sessionIdle方法中加入Session会话关闭的代码,这样session关闭就能传递到拦截器或者监听器中,然后实现重连。 connector.setHandler(new MyIoHandlerConnector()); connect(); } private void connect(){ ConnectFuture future = connector.connect(new InetSocketAddress(hostname, port)); future.awaitUninterruptibly(10000); session = future.getSession(); } private void reconnect(){ while (true){ try { Thread.sleep(3000); connect(); if (session != null && session.isConnected()) { LOGGER.info("断线重连成功"); break; } }catch (Exception e){ LOGGER.error("断线重连失败", e); } } } class MyIoServiceListener implements IoServiceListener{ public void serviceActivated(IoService ioService) throws Exception { } public void serviceIdle(IoService ioService, IdleStatus idleStatus) throws Exception { } public void serviceDeactivated(IoService ioService) throws Exception { } public void sessionCreated(IoSession ioSession) throws Exception { } public void sessionDestroyed(IoSession ioSession) throws Exception { reconnect(); } } class MyIoHandlerConnector extends IoHandlerAdapter{ @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { if(session != null){ //这里关闭session就会触发拦截器或者监听器,从而实现读写空闲时重连 session.close(true); } } @Override public void messageSent(IoSession session, Object message) throws Exception { } @Override public void messageReceived(IoSession session, Object message) throws Exception { String req = message==null?"":message.toString(); System.err.println("Client receive: "+req); } @Override public void sessionCreated(IoSession session) throws Exception { IoSessionConfig config = session.getConfig(); if (config instanceof SocketSessionConfig) { SocketSessionConfig sessionConfig = (SocketSessionConfig) config; sessionConfig.setKeepAlive(true);// 长连接 } System.out.println("Client session create"); } @Override public void sessionClosed(IoSession session) throws Exception { super.sessionClosed(session); System.out.println("Client session create"); } } public static void main(String[] args) { new MinaClient(); } }
标签:
原文地址:http://www.cnblogs.com/andyfengzp/p/5799743.html