Java Code Examples for io.netty.bootstrap.Bootstrap#group()

The following examples show how to use io.netty.bootstrap.Bootstrap#group() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NettyClientServerCommunicationSystemClientSide.java    From library with Apache License 2.0 6 votes vote down vote up
/**
 * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture.
 * sessionClientToReplica is replaced with the new connection. Removed redundant
 * code.
 */
public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac)
		throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {

	String str = this.clientId + ":" + replicaId;
	PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray());
	SecretKey authKey = fac.generateSecret(spec);

	Bootstrap b = new Bootstrap();
	b.group(workerGroup);
	b.channel(NioSocketChannel.class);
	b.option(ChannelOption.SO_KEEPALIVE, true);
	b.option(ChannelOption.TCP_NODELAY, true);
	b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
	b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec);
	b.handler(getChannelInitializer());

	ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId));

	NettyClientServerSession ncss = new NettyClientServerSession(
			channelFuture.channel(), replicaId);
	sessionClientToReplica.put(replicaId, ncss);

	return channelFuture;
}
 
Example 2
Source File: NettyClient.java    From dubbo-remoting-netty4 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new Bootstrap();
    // config
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(WORKER_GROUP);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.handler(new ChannelInitializer() {
        public void initChannel(Channel ch) {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline channelPipeline = ch.pipeline();
            channelPipeline.addLast("decoder", adapter.getDecoder());
            channelPipeline.addLast("encoder", adapter.getEncoder());
            channelPipeline.addLast("handler", nettyHandler);
        }
    });

}
 
Example 3
Source File: TestDnsServer.java    From armeria with Apache License 2.0 6 votes vote down vote up
public TestDnsServer(Map<DnsQuestion, DnsResponse> responses,
                     @Nullable ChannelInboundHandlerAdapter beforeDnsServerHandler) {
    this.responses = ImmutableMap.copyOf(responses);

    final Bootstrap b = new Bootstrap();
    b.channel(TransportType.datagramChannelType(CommonPools.workerGroup()));
    b.group(CommonPools.workerGroup());
    b.handler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            final ChannelPipeline p = ch.pipeline();
            p.addLast(new DatagramDnsQueryDecoder());
            p.addLast(new DatagramDnsResponseEncoder());
            if (beforeDnsServerHandler != null) {
                p.addLast(beforeDnsServerHandler);
            }
            p.addLast(new DnsServerHandler());
        }
    });

    channel = b.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
}
 
Example 4
Source File: NettyClient.java    From dubbo-remoting-netty4 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new Bootstrap();
    // config
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(WORKER_GROUP);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.handler(new ChannelInitializer() {
        public void initChannel(Channel ch) {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline channelPipeline = ch.pipeline();
            channelPipeline.addLast("decoder", adapter.getDecoder());
            channelPipeline.addLast("encoder", adapter.getEncoder());
            channelPipeline.addLast("handler", nettyHandler);
        }
    });

}
 
Example 5
Source File: ClientConnectionManager.java    From xio with Apache License 2.0 6 votes vote down vote up
public ChannelFuture connect() {
  if (connectionState == ClientConnectionState.NOT_CONNECTED) {
    connectionState = ClientConnectionState.CONNECTING;

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.channel(state.channelConfig.channel());
    bootstrap.group(state.channelConfig.workerGroup());
    bootstrap.handler(channelInitializer);
    ChannelFuture connectFuture = bootstrap.connect(state.remote);
    currentChannelFuture = connectFuture;
    currentChannelFuture.channel().closeFuture().addListener(releaseListener);
    connectFuture.addListener(connectionListener);
    return connectFuture;
  } else {
    return currentChannelFuture;
  }
}
 
Example 6
Source File: NettyClient.java    From dapeng-soa with Apache License 2.0 6 votes vote down vote up
protected Bootstrap initBootstrap() {
    AbstractByteBufAllocator allocator =
            SoaSystemEnvProperties.SOA_POOLED_BYTEBUF ?
                    PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT;
    bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds),
                    new SoaFrameDecoder(), //粘包和断包处理
                    new SoaIdleHandler(),
                    new SoaClientHandler(callBack));
        }
    });
    return bootstrap;
}
 
Example 7
Source File: StompClient.java    From hazelcastmq with Apache License 2.0 6 votes vote down vote up
/**
 * Connects to the remote server by opening a network connection and then
 * immediately sending the STOMP CONNECT frame. When the method returns, the
 * client is fully connected (at the network and STOMP layers) and can
 * immediately begin sending frames or subscribing to destinations.
 *
 * @throws InterruptedException if the connect operation is interrupted
 * @throws StompException if the STOMP CONNECT frame fails
 */
public void connect() throws InterruptedException, StompException {
  workerGroup = new NioEventLoopGroup();

  Bootstrap b = new Bootstrap();
  b.group(workerGroup);
  b.channel(NioSocketChannel.class);
  b.option(ChannelOption.SO_KEEPALIVE, true);
  b.handler(createHandler());

  // Start the client.
  ChannelFuture f = b.connect(host, port).sync();
  channel = f.channel();

  Frame request = FrameBuilder.connect(StompVersion.VERSION_1_2, host)
      .header(Headers.HEART_BEAT, format("%d,%d", HEARTBEAT_CL_SEND,
              HEARTBEAT_CL_RECV)).build();

  channel.writeAndFlush(request);

  Frame response = connectedListener.poll(10, TimeUnit.SECONDS);
  if (response == null) {
    channel.close().sync();
    throw new StompException("Connect failure: CONNECTED frame not received.");
  }
}
 
Example 8
Source File: NettyClient.java    From netty-learning-example with Apache License 2.0 6 votes vote down vote up
/**
 * 重连
 */
public void doConnect(Bootstrap bootstrap, EventLoopGroup eventLoopGroup) {
    try {
        if (bootstrap != null) {
            bootstrap.group(eventLoopGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new NettyClientInitializer());
            bootstrap.remoteAddress(host, port);
            f = bootstrap.connect().addListener((ChannelFuture futureListener) -> {
                final EventLoop eventLoop = futureListener.channel().eventLoop();
                if (!futureListener.isSuccess()) {
                    log.info("与服务端断开连接!在10s之后准备尝试重连!");
                    eventLoop.schedule(() -> doConnect(new Bootstrap(), eventLoop), 10, TimeUnit.SECONDS);
                }
            });
            if(initFalg){
                log.info("Netty客户端启动成功!");
                initFalg=false;
            }
        }
    } catch (Exception e) {
        log.info("客户端连接失败!"+e.getMessage());
    }

}
 
Example 9
Source File: KcpClient.java    From java-Kcp with Apache License 2.0 5 votes vote down vote up
public void init(ChannelConfig channelConfig) {
    if(channelConfig.isUseConvChannel()){
        int convIndex = 0;
        if(channelConfig.KcpTag){
            convIndex+=Ukcp.KCP_TAG;
        }
        if(channelConfig.getFecDataShardCount()!=0&&channelConfig.getFecParityShardCount()!=0){
            convIndex+= Fec.fecHeaderSizePlus2;
        }
        channelManager = new ConvChannelManager(convIndex);
    }else{
        channelManager = new ClientAddressChannelManager();
    }
    int cpuNum = Runtime.getRuntime().availableProcessors();
    if (disruptorExecutorPool == null) {
        this.disruptorExecutorPool = new DisruptorExecutorPool();
        for (int i = 0; i < cpuNum; i++) {
            disruptorExecutorPool.createDisruptorProcessor("disruptorExecutorPool" + i);
        }
    }
    nioEventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new Bootstrap();
    bootstrap.channel(NioDatagramChannel.class);
    bootstrap.group(nioEventLoopGroup);
    bootstrap.handler(new ChannelInitializer<NioDatagramChannel>() {
        @Override
        protected void initChannel(NioDatagramChannel ch) {
            ChannelPipeline cp = ch.pipeline();
            if(channelConfig.isCrc32Check()){
                Crc32Encode crc32Encode = new Crc32Encode();
                Crc32Decode crc32Decode = new Crc32Decode();
                cp.addLast(crc32Encode);
                cp.addLast(crc32Decode);
            }
            cp.addLast(new ClientChannelHandler(channelManager));
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(() -> stop()));
}
 
Example 10
Source File: ProtocolServersImpl.java    From ffwd with Apache License 2.0 5 votes vote down vote up
private AsyncFuture<ProtocolConnection> bindUDP(
    final Logger log, final Protocol protocol, ProtocolServer server, RetryPolicy policy
) {
    final Bootstrap b = new Bootstrap();

    b.group(worker);
    b.channel(NioDatagramChannel.class);
    b.handler(server.initializer());

    if (protocol.getReceiveBufferSize() != null) {
        b.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    final String host = protocol.getAddress().getHostString();
    final int port = protocol.getAddress().getPort();

    final RetryingProtocolConnection connection =
        new RetryingProtocolConnection(async, timer, log, policy, new ProtocolChannelSetup() {
            @Override
            public ChannelFuture setup() {
                return b.bind(host, port);
            }

            @Override
            public String toString() {
                return String.format("bind udp://%s:%d", host, port);
            }
        });

    return connection.getInitialFuture();
}
 
Example 11
Source File: NettyRpcClientInitializer.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Optional<Future> connect(SocketAddress socketAddress) {
    for (int i = 0; i < rpcConfig.getReconnectCount(); i++) {
        if (SocketManager.getInstance().noConnect(socketAddress)) {
            try {
                log.info("Try connect socket({}) - count {}", socketAddress, i + 1);
                Bootstrap b = new Bootstrap();
                b.group(workerGroup);
                b.channel(NioSocketChannel.class);
                b.option(ChannelOption.SO_KEEPALIVE, true);
                b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                b.handler(nettyRpcClientChannelInitializer);
                return Optional.of(b.connect(socketAddress).syncUninterruptibly());
            } catch (Exception e) {
                log.warn("Connect socket({}) fail. {}ms latter try again.", socketAddress, rpcConfig.getReconnectDelay());
                try {
                    Thread.sleep(rpcConfig.getReconnectDelay());
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                continue;
            }
        }
        // 忽略已连接的连接
        return Optional.empty();
    }

    log.warn("Finally, netty connection fail , socket is {}", socketAddress);
    clientInitCallBack.connectFail(socketAddress.toString());
    return Optional.empty();
}
 
Example 12
Source File: ProxyServer.java    From xio with Apache License 2.0 5 votes vote down vote up
protected ChannelFuture connectToDestination(EventLoop loop, ChannelHandler handler) {
  Bootstrap b = new Bootstrap();
  b.channel(NioSocketChannel.class);
  b.group(loop);
  b.handler(handler);
  return b.connect(intermediaryDestination());
}
 
Example 13
Source File: OioEventLoopTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testTooManyClientChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Bootstrap cb = new Bootstrap();
    cb.channel(OioSocketChannel.class);
    cb.group(g);
    cb.handler(new ChannelInboundHandlerAdapter());
    ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    f2.await();

    assertThat(f2.cause(), is(instanceOf(ChannelException.class)));
    assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels"));

    final CountDownLatch notified = new CountDownLatch(1);
    f2.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            notified.countDown();
        }
    });

    notified.await();
    g.shutdownGracefully();
}
 
Example 14
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final long TIMEOUT = 2000;
    for (ChannelHandler h: clientHandlers) {
        if (h instanceof ProxyHandler) {
            ((ProxyHandler) h).setConnectTimeoutMillis(TIMEOUT);
        }
    }

    final FailureTestHandler testHandler = new FailureTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    ChannelFuture cf = b.connect(DESTINATION).channel().closeFuture();
    boolean finished = cf.await(TIMEOUT * 2, TimeUnit.MILLISECONDS);
    finished &= testHandler.latch.await(TIMEOUT * 2, TimeUnit.MILLISECONDS);

    logger.debug("Recorded exceptions: {}", testHandler.exceptions);

    assertProxyHandlers(false);

    assertThat(testHandler.exceptions.size(), is(1));
    Throwable e = testHandler.exceptions.poll();
    assertThat(e, is(instanceOf(ProxyConnectException.class)));
    assertThat(String.valueOf(e), containsString("timeout"));
    assertThat(finished, is(true));
}
 
Example 15
Source File: UdpProtocol.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
public Bootstrap createBootstrap() {
    bootstrap = new Bootstrap();
    bootstrap.channel(NioDatagramChannel.class);
    bootstrap.group(eventLoopGroup);
    bootstrap.handler(newChannelInitializer());
    return bootstrap;
}
 
Example 16
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final SuccessTestHandler testHandler = new SuccessTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.AUTO_READ, ThreadLocalRandom.current().nextBoolean());
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    boolean finished = b.connect(destination).channel().closeFuture().await(10, TimeUnit.SECONDS);

    logger.debug("Received messages: {}", testHandler.received);

    if (testHandler.exceptions.isEmpty()) {
        logger.debug("No recorded exceptions on the client side.");
    } else {
        for (Throwable t : testHandler.exceptions) {
            logger.debug("Recorded exception on the client side: {}", t);
        }
    }

    assertProxyHandlers(true);

    assertThat(testHandler.received.toArray(), is(new Object[] { "0", "1", "2", "3" }));
    assertThat(testHandler.exceptions.toArray(), is(EmptyArrays.EMPTY_OBJECTS));
    assertThat(testHandler.eventCount, is(expectedEventCount));
    assertThat(finished, is(true));
}
 
Example 17
Source File: BGPDispatcherImpl.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private synchronized Bootstrap createClientBootStrap(final KeyMapping keys, final boolean reuseAddress,
        final InetSocketAddress localAddress) {
    final Bootstrap bootstrap = new Bootstrap();
    if (Epoll.isAvailable()) {
        bootstrap.channel(EpollSocketChannel.class);
        bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }
    if (keys != null && !keys.isEmpty()) {
        if (Epoll.isAvailable()) {
            bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
        } else {
            throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
        }
    }

    // Make sure we are doing round-robin processing
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, RECV_ALLOCATOR);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, WATER_MARK);
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);

    if (bootstrap.config().group() == null) {
        bootstrap.group(this.workerGroup);
    }
    bootstrap.localAddress(localAddress);

    return bootstrap;
}
 
Example 18
Source File: NettyClientService.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Override
public void connect() throws Exception {
       try {
           channelLock.writeLock().lock();

           initChannelHandlers(serviceContext);

           LinkedHashMap<String, ChannelHandler> handlers = getChannelHandlers();

           Bootstrap cb = new Bootstrap();
           // Fixme: use ITaskExecutor ?
           cb.group(nioEventLoopGroup);
           cb.channel(NioSocketChannel.class);
           cb.option(ChannelOption.SO_REUSEADDR, true);
           // we can configure java -Dio.netty.allocator.numDirectArenas=... -Dio.netty.allocator.numHeapArenas=...
           cb.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
           cb.handler(new ChannelInitializer<Channel>() {
               @Override
               protected void initChannel(Channel ch) throws Exception {
                   for (Entry<String, ChannelHandler> entry : handlers.entrySet()) {
                       ch.pipeline().addLast(entry.getKey(), entry.getValue());
                   }
                   // add exception handler for inbound messages
                   // outbound exceptions will be routed here by ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE
                   ch.pipeline().addLast(new ExceptionInboundHandler(nettySession::onExceptionCaught));

               }
           });

           Channel localChannel = cb.connect(getHost(), getPort())
                   .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE)
                   .addListener(ChannelFutureListener.CLOSE_ON_FAILURE)
                   .awaitUninterruptibly()
                   .channel();

           initChannelCloseFuture(localChannel);
           setChannel(localChannel);
       } finally {
           channelLock.writeLock().unlock();
       }
}
 
Example 19
Source File: HttpChannelPool.java    From armeria with Apache License 2.0 4 votes vote down vote up
HttpChannelPool(HttpClientFactory clientFactory, EventLoop eventLoop,
                SslContext sslCtxHttp1Or2, SslContext sslCtxHttp1Only,
                ConnectionPoolListener listener) {
    this.eventLoop = eventLoop;
    pool = newEnumMap(
            Map.class,
            unused -> new HashMap<>(),
            SessionProtocol.H1, SessionProtocol.H1C,
            SessionProtocol.H2, SessionProtocol.H2C);
    pendingAcquisitions = newEnumMap(
            Map.class,
            unused -> new HashMap<>(),
            SessionProtocol.HTTP, SessionProtocol.HTTPS,
            SessionProtocol.H1, SessionProtocol.H1C,
            SessionProtocol.H2, SessionProtocol.H2C);
    allChannels = new IdentityHashMap<>();
    this.listener = listener;

    final Bootstrap baseBootstrap = clientFactory.newBootstrap();
    baseBootstrap.group(eventLoop);
    bootstraps = newEnumMap(
            Bootstrap.class,
            desiredProtocol -> {
                final SslContext sslCtx = desiredProtocol == SessionProtocol.H1 ||
                                          desiredProtocol == SessionProtocol.H1C ? sslCtxHttp1Only
                                                                                 : sslCtxHttp1Or2;
                final Bootstrap bootstrap = baseBootstrap.clone();
                bootstrap.handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        configureProxy(ch, proxyConfig, sslCtx);
                        ch.pipeline().addLast(
                                new HttpClientPipelineConfigurator(clientFactory, desiredProtocol, sslCtx));
                    }
                });
                return bootstrap;
            },
            SessionProtocol.HTTP, SessionProtocol.HTTPS,
            SessionProtocol.H1, SessionProtocol.H1C,
            SessionProtocol.H2, SessionProtocol.H2C);
    meterRegistry = clientFactory.meterRegistry();
    connectTimeoutMillis = (Integer) baseBootstrap.config().options()
                                                  .get(ChannelOption.CONNECT_TIMEOUT_MILLIS);
    useHttp1Pipelining = clientFactory.useHttp1Pipelining();
    idleTimeoutMillis = clientFactory.idleTimeoutMillis();
    pingIntervalMillis = clientFactory.pingIntervalMillis();
    proxyConfig = clientFactory.proxyConfig();
}
 
Example 20
Source File: MqttClientImpl.java    From smartacus-mqtt-broker with Apache License 2.0 4 votes vote down vote up
private Future<MqttConnectResult> connect(String host, int port, boolean reconnect) {
    if (this.eventLoop == null) {
        this.eventLoop = new NioEventLoopGroup();
    }
    this.host = host;
    this.port = port;
    Promise<MqttConnectResult> connectFuture = new DefaultPromise<>(this.eventLoop.next());
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoop);
    bootstrap.channel(clientConfig.getChannelClass());
    bootstrap.remoteAddress(host, port);
    bootstrap.handler(new MqttChannelInitializer(connectFuture, host, port, clientConfig.getSslContext()));
    ChannelFuture future = bootstrap.connect();

    future.addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            MqttClientImpl.this.channel = f.channel();
            MqttClientImpl.this.channel.closeFuture().addListener((ChannelFutureListener) channelFuture -> {
                if (isConnected()) {
                    return;
                }
                ChannelClosedException e = new ChannelClosedException("Channel is closed!");
                if (callback != null) {
                    callback.connectionLost(e);
                }
                pendingSubscriptions.clear();
                serverSubscriptions.clear();
                subscriptions.clear();
                pendingServerUnsubscribes.clear();
                qos2PendingIncomingPublishes.clear();
                pendingPublishes.clear();
                pendingSubscribeTopics.clear();
                handlerToSubscribtion.clear();
                publish("TEST_TOPIC", Unpooled.wrappedBuffer("测试消息".getBytes()));
                scheduleConnectIfRequired(host, port, true);
            });
        } else {
            scheduleConnectIfRequired(host, port, reconnect);
        }
    });
    return connectFuture;
}