private void keepAliveFilterForIdleStatus(IdleStatus status) throws Exception { NioSocketConnector connector = new NioSocketConnector(); KeepAliveFilter filter = new KeepAliveFilter(new ClientFactory(), status, EXCEPTION, INTERVAL, TIMEOUT); filter.setForwardEvent(true); connector.getFilterChain().addLast("keep-alive", filter); final AtomicBoolean gotException = new AtomicBoolean(false); connector.setHandler( new IoHandlerAdapter() { @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { // cause.printStackTrace(); gotException.set(true); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { // Do nothing } }); ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", port)).awaitUninterruptibly(); IoSession session = future.getSession(); assertNotNull(session); Thread.sleep((INTERVAL + TIMEOUT + 1) * 1000); assertFalse("got an exception on the client", gotException.get()); session.close(true); connector.dispose(); }
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); }
private NioSocketConnector setupConnector(IoHandlerAdapter handler) { NioSocketConnector connector = new NioSocketConnector(); connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 300); connector.setConnectTimeoutCheckInterval(5); connector .getFilterChain() .addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); connector.setHandler(handler); return connector; }
private void init() { connector = new NioSocketConnector(); bh = new BotHandler(username, password, roomId); connector.setHandler(bh); DefaultIoFilterChainBuilder chain = connector.getFilterChain(); log.debug("connecing to the server..."); ConnectFuture connFuture = connector.connect( new InetSocketAddress(ServerConfig.gameServerAddress, ServerConfig.gameServerPort)); connFuture.awaitUninterruptibly(); }
/** * Cleans-up any resources after a connection has terminated. Should be called when the connection * is disconnected and reconnect is not desired. */ void finishConnection() { NioSocketConnector conn = this.connector; if (conn != null) { this.connector = null; conn.dispose(); for (ConnectionListener listener : this.connectionListeners) { listener.connectionEnded(this); } } ExecutorFilter execs = this.executors; if (execs != null) { this.executors = null; execs.destroy(); } }
/** 注销当前连接 */ public void dispose() { if (connector != null) { connector.dispose(); } if (healthDaemon != null) { healthDaemon.stopHeartBeat(); } }
/** 初始化连接类 */ public synchronized void initConnector(IoHandler handler) { if (connector == null) { connector = new NioSocketConnector(); // 设置缓存大小 connector.getSessionConfig().setMaxReadBufferSize(2048); // 添加过滤器 connector .getFilterChain() .addLast( "codec", new ProtocolCodecFilter(new ExpressCodecFactory(Charset.forName("UTF-8")))); // 设置日志过滤器 LoggingFilter loggingFilter = new LoggingFilter(); loggingFilter.setMessageReceivedLogLevel(LogLevel.DEBUG); loggingFilter.setMessageSentLogLevel(LogLevel.DEBUG); connector.getFilterChain().addLast("logger", loggingFilter); // 添加登录过滤器 connector.getFilterChain().addLast("loginFilter", new TCPLoginFilter()); // 添加登出过滤器 connector.getFilterChain().addLast("logoutFilter", new TCPLogoutFilter()); // 防回流过滤器 connector.getFilterChain().addLast("backFlowFilter", new BackFlowFilter()); // 添加业务逻辑处理器类 connector.setHandler(handler); } }
/** * 根据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()); }
@Override public void run() { running = true; finished = false; NioSocketConnector connector = setupConnector(clientHandler); IoSession session = createSession(connector, socketAddress); while (running) { String processedObservation = null; try { processedObservation = queue.poll(500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.error("Interrupted while polling the processed observation queue"); } if (processedObservation != null) session.write(processedObservation); } session.getCloseFuture().awaitUninterruptibly(); // closed when idle in handler connector.dispose(); finished = true; }
/** * 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(); }
private CommandMinaClient() throws java.net.ConnectException { NioSocketConnector connector = new NioSocketConnector(); // 创建接收数据的过滤器 DefaultIoFilterChainBuilder chain = connector.getFilterChain(); // 设定这个过滤器将以对象为单位读取数据 ProtocolCodecFilter filter = new ProtocolCodecFilter(new ObjectSerializationCodecFactory()); // 设定服务器端的消息处理器:一个SamplMinaServerHandler对象, chain.addLast("objectFilter", filter); // 设定服务器端的消息处理器:一个 SamplMinaServerHandler 对象, connector.setHandler(new CommandMinaClientHanlder()); // Set connect timeout. connector.setConnectTimeoutCheckInterval(30); // 连结到服务器: ConnectFuture cf = connector.connect(new InetSocketAddress("159.226.95.156", 9900)); // Wait for the connection attempt to be finished. cf.awaitUninterruptibly(); session = cf.getSession(); }
public void connect(InetAddress ia, int port) { connector = new NioSocketConnector(); connector .getFilterChain() .addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); if (logger.isDebugEnabled()) { LoggingFilter logFilter = new LoggingFilter(); logFilter.setMessageSentLogLevel(LogLevel.DEBUG); logFilter.setMessageReceivedLogLevel(LogLevel.DEBUG); connector.getFilterChain().addLast("logger", logFilter); } connector.setHandler(this); ConnectFuture future = connector.connect(new InetSocketAddress(ia, port)); future.awaitUninterruptibly(); if (!future.isConnected()) { logger.error("Connection failed"); } session = future.getSession(); }
public void socketServer() { // 创建一个socket连接 NioSocketConnector connector = new NioSocketConnector(); // 消息核心处理器 connector.setHandler(new MinaClientHanlder()); // 设置链接超时时间 connector.setConnectTimeoutCheckInterval(30); // 获取过滤器链 DefaultIoFilterChainBuilder chain = connector.getFilterChain(); ProtocolCodecFilter filter = new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))); // 添加编码过滤器 处理乱码、编码问题 chain.addLast("objectFilter", filter); // 连接服务器,知道端口、地址 ConnectFuture cf = connector.connect(new InetSocketAddress(App.address, App.bindPort)); // 等待连接创建完成 cf.awaitUninterruptibly(); if (cf.isConnected()) { App.isConnected = true; System.out.println("等待连接断开"); // 等待连接断开 cf.getSession().getCloseFuture().awaitUninterruptibly(); } else { System.out.println("连接断开"); App.isConnected = false; } System.out.println("----dispose"); connector.dispose(); System.out.println("dispose----"); }
@Test public void testWriteUsingSocketTransport() throws Exception { NioSocketAcceptor acceptor = new NioSocketAcceptor(); acceptor.setReuseAddress(true); SocketAddress address = new InetSocketAddress("localhost", AvailablePortFinder.getNextAvailable()); NioSocketConnector connector = new NioSocketConnector(); // Generate 4MB of random data byte[] data = new byte[4 * 1024 * 1024]; new Random().nextBytes(data); byte[] expectedMd5 = MessageDigest.getInstance("MD5").digest(data); M message = createMessage(data); SenderHandler sender = new SenderHandler(message); ReceiverHandler receiver = new ReceiverHandler(data.length); acceptor.setHandler(sender); connector.setHandler(receiver); acceptor.bind(address); connector.connect(address); sender.latch.await(); receiver.latch.await(); acceptor.dispose(); assertEquals(data.length, receiver.bytesRead); byte[] actualMd5 = receiver.digest.digest(); assertEquals(expectedMd5.length, actualMd5.length); for (int i = 0; i < expectedMd5.length; i++) { assertEquals(expectedMd5[i], actualMd5[i]); } }
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(); }
public void doConnnect() { // 连结到服务器: ConnectFuture cf = connector.connect(new InetSocketAddress(remoteServerHost, remoteServerPort)); cf.addListener( new IoFutureListener<ConnectFuture>() { public void operationComplete(ConnectFuture future) { if (future.isConnected()) { logger.info("连接成功:" + getServerInfo()); } else { logger.error("连接失败:" + ",原因:" + future.getException()); // 启动连接失败时定时重连 scheduleConnect(); } } }); }
private IoSession createSession(NioSocketConnector connector, InetSocketAddress socketAddress) { IoSession session; for (; ; ) { try { ConnectFuture future = connector.connect(socketAddress); future.awaitUninterruptibly(); session = future.getSession(); break; } catch (RuntimeIoException e) { logger.error("Error while obtaining sensor server session", e); try { Thread.sleep(5000); } catch (InterruptedException e1) { logger.error("Error while sleeping", e); } } } return session; }
/** * @ClassName: TongbuClient @Description: mina客户端=====同步 * * @author xubin * @date 2012-9-10 下午6:33:53 */ public class TongbuClient { NioSocketConnector connector = new NioSocketConnector(); DefaultIoFilterChainBuilder chain = connector.getFilterChain(); CommResultInfo info; /** * 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 CommResultInfo getResult() { return info; } }
public void connect(String host, int port, CmdListener cmdListener) { final CmdListener fCmdListener = cmdListener; // --start // IoBuffer.setUseDirectBuffer(false); // IoBuffer.setAllocator(new QSIoBufferAllocater()); // --end ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port)); connectFuture.addListener( new IoFutureListener<ConnectFuture>() { public void operationComplete(ConnectFuture future) { if (!future.isConnected()) { fCmdListener.onException(new Exception("连接超时")); } else { future.getSession().setAttribute("CmdListener", fCmdListener); future .getSession() .getConfig() .setIdleTime(IdleStatus.WRITER_IDLE, fCmdListener.getWriteTimeout()); future.getSession().getConfig().setReadBufferSize(3000); future.getSession().write(fCmdListener.getCmdResuest()); } } }); }
public void close() { connector.dispose(); }