/** * Attempts a connection to the world model. * * @param timeout the connection timeout value in milliseconds. * @return {@code true} if the attempt succeeds, else {@code false}. */ protected boolean _connect(long timeout) { log.debug("Attempting connection..."); ConnectFuture connFuture = this.connector.connect(new InetSocketAddress(this.host, this.port)); if (!connFuture.awaitUninterruptibly(timeout)) { log.warn( "Unable to connect to world model after {}ms.", Long.valueOf(this.connectionTimeout)); return false; } if (!connFuture.isConnected()) { log.debug("Failed to connect."); return false; } try { log.debug("Attempting connection to {}:{}.", this.host, Integer.valueOf(this.port)); this.session = connFuture.getSession(); } catch (RuntimeIoException ioe) { log.error( String.format( "Could not create session to World Model (C) %s:%d.", this.host, Integer.valueOf(this.port)), ioe); return false; } return true; }
/** * Connect by tcp. * * @param host the host * @param port the port * @return the t conn */ public static synchronized TConn connectByTcp(String host, int port, long timeout) { TimeStamp t = TimeStamp.create(); try { if (tcpconnector == null) { tcpconnector = new TDCConnector(); } tcpconnector.connector.setConnectTimeoutMillis(timeout); ConnectFuture connFuture = tcpconnector.connector.connect(new InetSocketAddress(host, port)); connFuture.awaitUninterruptibly(timeout); IoSession session = connFuture.getSession(); TConn c = new TConn(session); session.setAttribute("conn", c); return c; } catch (Exception e) { log.error( "error, [" + host + ":" + port + "], cost: " + t.past() + "ms, timeout=" + timeout, e); } return null; }
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----"); }
public void testAcceptorFilterChain() throws Exception { int port = AvailablePortFinder.getNextAvailable(1024 + 1000); IoFilter mockFilter = new MockFilter(); IoHandler mockHandler = new MockHandler(); acceptor.getFilterChain().addLast("mock", mockFilter); acceptor.setHandler(mockHandler); acceptor.bind(new InetSocketAddress(port)); try { connector.setHandler(new IoHandlerAdapter()); ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", port)); future.awaitUninterruptibly(); WriteFuture writeFuture = future.getSession().write(IoBuffer.allocate(16).putInt(0).flip()); writeFuture.awaitUninterruptibly(); Assert.assertTrue(writeFuture.isWritten()); future.getSession().close(true); for (int i = 0; i < 30; i++) { if (result.length() == 2) { break; } Thread.sleep(100); } Assert.assertEquals("FH", result); } finally { acceptor.unbind(); } }
public void run() { while (true) { MinaNode node = (MinaNode) BisonContext.this.connectQueue.poll(); if ((node == null) && (BisonContext.this.connectQueue.size() == 0)) { BisonContext.this.processor = null; break; } ConnectFuture cf = BisonContext.this.connector.connect(node.getRemoteAddress()); cf.awaitUninterruptibly(); if (!cf.isConnected()) { BisonContext.this.logger.info("建立连接失败 " + node.toString()); try { if (BisonContext.this.connectQueue.size() == 0) Thread.sleep(5000L); else Thread.sleep(1000L); } catch (Exception localException) { } BisonContext.this.connectQueue.offer(node); continue; } cf.getSession().setAttribute(SESSION_NODE_KEY, node); node.setSession(cf.getSession()); node.setConnected(true); BisonContext.this.logger.info("建立连接成功 " + node.toString()); } }
public boolean send(String message) { if (future.isConnected()) { // 等待连接创建完成 future.awaitUninterruptibly(); // 获取当前session session = future.getSession(); session.write(message); return true; } else { return false; } }
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(); }
private void openConnection() { if (LOG.isDebugEnabled()) { LOG.debug( "Creating connector to address: {} using connector: {} timeout: {} millis.", new Object[] {address, connector, timeout}); } // connect and wait until the connection is established if (connectorConfig != null) { connector.getSessionConfig().setAll(connectorConfig); } connector.setHandler(new ResponseHandler()); ConnectFuture future = connector.connect(address); future.awaitUninterruptibly(); session = future.getSession(); }
private void init() { connector = new NioSocketConnector(); connector.setConnectTimeoutMillis(15000); connector.setHandler(this); JsonProtocalCodecFactory factory = new JsonProtocalCodecFactory(Charset.forName("UTF-8")); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(factory)); ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port)); connectFuture.awaitUninterruptibly(); // 同步,等待,直到连接完成 if (connectFuture.isDone()) { if (!connectFuture.isConnected()) { // 若在指定时间内没连接成功,则抛出异常 connector.dispose(); // 不关闭的话会运行一段时间后抛出,too many open connector = null; } } lastTime = System.currentTimeMillis(); }
/** * 根据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()); }
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; }
/** * Connect by udp. * * @param host the host * @param port the port * @return the t conn */ public static synchronized TConn connectByUdp(String host, int port) { try { if (udpconnector == null) { udpconnector = new UDCConnector(); } ConnectFuture connFuture = udpconnector.connector.connect(new InetSocketAddress(host, port)); connFuture.awaitUninterruptibly(); IoSession session = connFuture.getSession(); TConn c = new TConn(session); session.setAttribute("conn", c); return c; } catch (Exception e) { log.error("[" + host + ":" + port + "]", e); } return null; }
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(); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Override protected void startConnector(String server, int port) { socketConnector = new NioSocketConnector(); socketConnector.setHandler(ioHandler); ConnectFuture future = socketConnector.connect(new InetSocketAddress(server, port)); future.addListener( new IoFutureListener() { public void operationComplete(IoFuture future) { try { // will throw RuntimeException after connection error future.getSession(); } catch (Throwable e) { // if there isn't an ClientExceptionHandler set, a // RuntimeException may be thrown in handleException handleException(e); // to get here you must have an exception handler set socketConnector.dispose(); } } }); future.awaitUninterruptibly(CONNECTOR_WORKER_TIMEOUT); }
public static void main(String[] args) { // 创建一个非阻塞的客户端程序 IoConnector connector = new NioSocketConnector(); // 设置链接超时时间 connector.setConnectTimeout(30000); // 设置过滤器 connector .getFilterChain() .addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue()))); // 添加业务逻辑处理器类 connector.setHandler(new Demo1ClientHandler()); IoSession session = null; try { ConnectFuture future = connector.connect(new InetSocketAddress(HOST, PORT)); // 创建连接 future.awaitUninterruptibly(); // 等待连接创建完成 session = future.getSession(); // 获得session String sendPhone = "13681803609"; // 当前发送人的手机号码 String receivePhone = "13721427169"; // 接收人手机号码 String message = "测试发送短信,这个是短信信息哦,当然长度是有限制的哦...."; String msg = sendPhone + ";" + receivePhone + ";" + message; session.write(msg); // 发送给移动服务端 } catch (Exception e) { logger.error("客户端链接异常...", e); } session.getCloseFuture().awaitUninterruptibly(); // 等待连接断开 connector.dispose(); }
@Override public boolean awaitUninterruptibly(long timeoutMillis) { return connectFuture.awaitUninterruptibly(timeoutMillis); }
/* */ public void startup() /* */ { /* */ try /* */ { /* 77 */ this.connector = new NioSocketConnector(); /* 78 */ this.connector.setConnectTimeoutMillis(30000L); /* 79 */ this.connector .getFilterChain() .addLast("codec", new ProtocolCodecFilter(new JT808CodecFactory())); /* 80 */ this.connector.setHandler(this.handler); /* */ /* 82 */ ConnectFuture future = this.connector.connect(this.address); /* 83 */ future.awaitUninterruptibly(); /* 84 */ if ((future.isDone()) && /* 85 */ (!future.isConnected())) { /* 86 */ this.connector.dispose(); /* 87 */ log.error("未在时限内建立连接"); /* 88 */ return; /* */ } /* */ /* 91 */ this.session = future.getSession(); /* */ /* 93 */ log.info("try to connect " + this.address); /* */ /* 95 */ if (this.sendThread == null) { /* 96 */ this.sendThread = new Thread( new Runnable() /* */ { /* */ public void run() { /* 99 */ long outmemorytime = 0L; /* */ while (true) /* */ try { /* 102 */ Thread.sleep(10L); /* 103 */ DistributeClient.this.write( (UnitPackJT808) DistributeClient.this.distributeQueue.poll()); /* */ /* 105 */ if ((outmemorytime == 0L) && (DistributeClient.this.distributeMsgId.size() > Constants.OUTOFMEMORY / 2)) { /* 106 */ outmemorytime = System.currentTimeMillis(); /* */ } /* 108 */ if (outmemorytime != 0L) /* 109 */ if (DistributeClient.this.distributeMsgId.size() >= Constants.OUTOFMEMORY) { /* 110 */ DistributeClient.log.info("drop message!"); /* 111 */ DistributeClient.this.distributeQueue.clear(); /* 112 */ outmemorytime = 0L; /* */ } /* 114 */ else if (System.currentTimeMillis() - outmemorytime > 300000L) { /* 115 */ DistributeClient.log.info("drop message!"); /* 116 */ DistributeClient.this.distributeQueue.clear(); /* 117 */ outmemorytime = 0L; /* */ } /* */ } /* */ catch (Exception e) /* */ { /* 122 */ DistributeClient.this.rebuildSession(); /* */ } /* */ } /* */ }); /* 127 */ this.sendThread.start(); /* */ } /* */ } catch (Exception e) { /* 130 */ rebuildSession(); /* */ } /* */ }
/** {@inheritDoc} */ @SuppressWarnings("resource") @Override public void sessionCreated(IoSession session) throws Exception { boolean isClient = session.getRemoteAddress().equals(forward); if (log.isDebugEnabled()) { log.debug("Is downstream: " + isClient); session.getFilterChain().addFirst("protocol", new ProtocolCodecFilter(codecFactory)); } session.getFilterChain().addFirst("proxy", new ProxyFilter(isClient ? "client" : "server")); if (true) { String fileName = System.currentTimeMillis() + '_' + forward.getHostName() + '_' + forward.getPort() + '_' + (isClient ? "DOWNSTREAM" : "UPSTREAM"); File headersFile = loader.getResource(dumpTo + fileName + ".cap").getFile(); headersFile.createNewFile(); File rawFile = loader.getResource(dumpTo + fileName + ".raw").getFile(); rawFile.createNewFile(); FileOutputStream headersFos = new FileOutputStream(headersFile); WritableByteChannel headers = headersFos.getChannel(); FileOutputStream rawFos = new FileOutputStream(rawFile); WritableByteChannel raw = rawFos.getChannel(); IoBuffer header = IoBuffer.allocate(1); header.put((byte) (isClient ? 0x00 : 0x01)); header.flip(); headers.write(header.buf()); session.getFilterChain().addFirst("dump", new NetworkDumpFilter(headers, raw)); } // session.getFilterChain().addLast("logger", new LoggingFilter() ); if (!isClient) { log.debug("Connecting.."); IoConnector connector = new NioSocketConnector(); connector.setHandler(this); ConnectFuture future = connector.connect(forward); future.awaitUninterruptibly(); // wait for connect, or timeout if (future.isConnected()) { if (log.isDebugEnabled()) { log.debug("Connected: {}", forward); } IoSession client = future.getSession(); client.setAttribute(ProxyFilter.FORWARD_KEY, session); session.setAttribute(ProxyFilter.FORWARD_KEY, client); } } super.sessionCreated(session); }