public static CmdClient getCmdClient(long connectTimeoutInMillis) { if (cmdClient == null) { cmdClient = new CmdClient(connectTimeoutInMillis); } else if (connector.getConnectTimeoutMillis() != connectTimeoutInMillis) { connector.setConnectTimeoutMillis(connectTimeoutInMillis); } return cmdClient; }
private CmdClient(long connectTimeoutInMillis) { connector.setConnectTimeoutMillis(connectTimeoutInMillis); connector .getFilterChain() .addLast( "codec", new ProtocolCodecFilter(new CmdRequestEncoder(), new CmdResponseDecoder())); connector.getFilterChain().addLast("threadPool", new ExecutorFilter(executor)); connector.setHandler(this); }
/** * 根据host和port新建一个IoSession连接 * * @param host 连接主机IP * @param port 连接端口 * @param timeout 未收到数据超时时间/秒 */ @Override public void connect(String host, int port, int timeout) throws Exception { connector.getSessionConfig().setIdleTime(IdleStatus.READER_IDLE, timeout); log.debug("超时时间:" + timeout + "秒"); // 设置连接超时时间 connector.setConnectTimeoutMillis(ExpressConstant.CONNECT_TIMEOUT); // 创建连接 ConnectFuture future = connector.connect(new InetSocketAddress(host, port)); // 等待连接创建完成 future.awaitUninterruptibly(); // 得到连接Session session = future.getSession(); // 设置Session同步锁对象 session.setAttribute(ExpressConstant.SESSION_LOCK, new LockExpress()); }
/** * Title: * * <p>Desc:初始化客户端信息 * * @param message * @throws UnsupportedEncodingException */ public TongbuClient(Object message, String url, int port) { chain.addLast("logging", new LoggingFilter()); // 添加日志过滤器 chain.addLast("myChin", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); if (message instanceof String) { connector.setHandler(new ClientHandler((String) message)); } else if (message instanceof CommEntity) { connector.setHandler(new ClientHandler((CommEntity) message)); } connector.setConnectTimeoutMillis(10000); SocketSessionConfig cfg = connector.getSessionConfig(); cfg.setUseReadOperation(true); IoSession session = connector.connect(new InetSocketAddress(url, port)).awaitUninterruptibly().getSession(); ReadFuture readFuture = session.read(); readFuture.awaitUninterruptibly(); this.info = (CommResultInfo) readFuture.getMessage(); session.close(true); session.getService().dispose(); }
public void init() { // Create TCP/IP connector. connector = new NioSocketConnector(); // 创建接收数据的过滤器 DefaultIoFilterChainBuilder chain = connector.getFilterChain(); // 自动重连 chain.addLast( "reConnect", new IoFilterAdapter() { public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { logger.error("连接被关闭:" + getServerInfo()); scheduleConnect(); } }); // 设定这个过滤器将一行一行(/r/n)的读取数据 chain.addLast("protocolCodecFilter", new ProtocolCodecFilter(new TextLineCodecFactory())); // 设定服务器端的消息处理器:一个MinaClientHandler对象, connector.setHandler(ioHandler); // Set connect timeout. connector.setConnectTimeoutMillis(30 * 1000); doConnnect(); }