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(); }
@Override public boolean isDone() { return connectFuture.isDone(); }
/* */ 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(); /* */ } /* */ }