Java Code Examples for io.netty.bootstrap.Bootstrap#channel()
The following examples show how to use
io.netty.bootstrap.Bootstrap#channel() .
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: NettyClientConnector.java From rpc-benchmark with Apache License 2.0 | 6 votes |
private void doConnect(EventLoopGroup loupGroup, Class<? extends SocketChannel> serverChannelClass, boolean isEpoll) throws InterruptedException { final Bootstrap bootstrap = new Bootstrap(); if (isEpoll) { bootstrap.option(EpollChannelOption.SO_REUSEPORT, true); } bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024); bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, // new WriteBufferWaterMark(1024 * 1024, 2048 * 1024)); bootstrap.group(loupGroup); bootstrap.channel(serverChannelClass); bootstrap.handler(new BenchmarkChannelInitializer(futureContainer)); for (int i = 0; i < CONNECT_COUNT; i++) { channels[i] = bootstrap.connect(host, port).sync().channel(); queues[i] = new MpscAtomicArrayQueue<>(4 * 1024); } }
Example 2
Source File: Client.java From push with Apache License 2.0 | 6 votes |
public void run() { workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); // b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4)); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("decoder", new MsgPackDecode()); pipeline.addLast("encoder", new MsgPackEncode()); pipeline.addLast(ClientConfiguration.clientHandler()); } }); channel = b.connect(clientProperties.getServerHost(), clientProperties.getServerPort()).sync().channel(); status = Status.START; channel.closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } status = Status.STOP; }
Example 3
Source File: AbstractNettyClient.java From sailfish-core with Apache License 2.0 | 6 votes |
@Override public void connect() throws Exception { Bootstrap cb = new Bootstrap(); cb.group(nioEventLoopGroup); cb.channel(NioSocketChannel.class); cb.option(ChannelOption.SO_REUSEADDR, true); cb.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); cb.handler(NOOP_CHANNEL_INITIALIZER); Channel localChannel = cb.connect(getHost(), getPort()) .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) .addListener(ChannelFutureListener.CLOSE_ON_FAILURE) .awaitUninterruptibly() .channel(); mainSession = createSession(localChannel); mainSession.withWriteLock(this::initChannel); mainSession.withWriteLock(this::initChannelCloseFuture); }
Example 4
Source File: JT809Server.java From jt809-tcp-server with MIT License | 6 votes |
/** * 从链路(客户端)引导入口 * @param group * @throws Exception */ private void runClient(EventLoopGroup group) throws Exception { String ip = clientConfig.getTcpIp(); Integer port = clientConfig.getTcpPort(); try { Bootstrap client = new Bootstrap(); client.group(group); client.channel(NioSocketChannel.class); client.option(ChannelOption.TCP_NODELAY, true); client.handler(jt809ClientChannelInit); ChannelFuture channelFuture = client.connect(ip, port).sync(); channelFuture.addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { log.info("nettyClient run success,TCP-IP:{},TCP-PORT:{}",ip,port); clientChannel = channelFuture.channel(); } } }); }catch (Exception e){ log.error("nettyClient run fail"); e.printStackTrace(); } }
Example 5
Source File: NettyMessagingService.java From atomix with Apache License 2.0 | 5 votes |
/** * Bootstraps a new channel to the given address. * * @param address the address to which to connect * @return a future to be completed with the connected channel */ private CompletableFuture<Channel> bootstrapClient(Address address) { CompletableFuture<Channel> future = new OrderedFuture<>(); final InetAddress resolvedAddress = address.address(true); if (resolvedAddress == null) { future.completeExceptionally(new IllegalStateException("Failed to bootstrap client (address " + address.toString() + " cannot be resolved)")); return future; } Bootstrap bootstrap = new Bootstrap(); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024)); bootstrap.option(ChannelOption.SO_RCVBUF, 1024 * 1024); bootstrap.option(ChannelOption.SO_SNDBUF, 1024 * 1024); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); bootstrap.group(clientGroup); // TODO: Make this faster: // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0 bootstrap.channel(clientChannelClass); bootstrap.remoteAddress(resolvedAddress, address.port()); if (enableNettyTls) { try { bootstrap.handler(new SslClientChannelInitializer(future, address)); } catch (SSLException e) { return Futures.exceptionalFuture(e); } } else { bootstrap.handler(new BasicClientChannelInitializer(future)); } bootstrap.connect().addListener(f -> { if (!f.isSuccess()) { future.completeExceptionally(f.cause()); } }); return future; }
Example 6
Source File: SimplePbrpcClient.java From navi-pbrpc with Apache License 2.0 | 5 votes |
/** * Creates a new instance of ShortLiveConnectionPbrpcClient. * * @param pbrpcClientConfiguration * @param isShortLiveConn * 是否是短连接调用,如果是则表示每次都重新新建channel * @param ip * @param port * @param connTimeout * @param readTimeout */ SimplePbrpcClient(PbrpcClientConfiguration pbrpcClientConfiguration, boolean isShortLiveConn, String ip, int port, int connTimeout, int readTimeout) { if (pbrpcClientConfiguration != null) { this.pbrpcClientConfiguration = pbrpcClientConfiguration; } this.ip = ip; this.port = port; this.connTimeout = connTimeout; this.readTimeout = readTimeout; this.isShortAliveConn = isShortLiveConn; bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.connTimeout); bootstrap.option(ChannelOption.SO_KEEPALIVE, this.pbrpcClientConfiguration.isSoKeepalive()); bootstrap.option(ChannelOption.SO_REUSEADDR, this.pbrpcClientConfiguration.isSoReuseaddr()); bootstrap.option(ChannelOption.TCP_NODELAY, this.pbrpcClientConfiguration.isTcpNodelay()); bootstrap.option(ChannelOption.SO_RCVBUF, this.pbrpcClientConfiguration.getSoRcvbuf()); bootstrap.option(ChannelOption.SO_SNDBUF, this.pbrpcClientConfiguration.getSoSndbuf()); ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new PbrpcMessageSerializer()); ch.pipeline().addLast(new PbrpcMessageDeserializer()); ch.pipeline().addLast(new PbrpcClientHandler()); } }; eventLoopGroup = new NioEventLoopGroup(); bootstrap.group(eventLoopGroup).handler(initializer); startTimeoutEvictor(); }
Example 7
Source File: AbstractEndpointClient.java From hermes with Apache License 2.0 | 5 votes |
private Bootstrap createBootstrap(final Endpoint endpoint, final EndpointChannel endpointChannel) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(m_eventLoopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true)// .option(ChannelOption.TCP_NODELAY, true)// .option(ChannelOption.SO_SNDBUF, m_config.getNettySendBufferSize())// .option(ChannelOption.SO_RCVBUF, m_config.getNettyReceiveBufferSize()); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( // new DefaultNettyChannelOutboundHandler(), // new NettyDecoder(), // new MagicNumberAndLengthPrepender(), // new NettyEncoder(), // new IdleStateHandler(m_config.getEndpointChannelReadIdleTime(), // m_config.getEndpointChannelWriteIdleTime(), // m_config.getEndpointChannelMaxIdleTime()), // new DefaultClientChannelInboundHandler(m_commandProcessorManager, endpoint, endpointChannel, AbstractEndpointClient.this, m_config)); } }); return bootstrap; }
Example 8
Source File: FtdClientPool.java From ftdc with Apache License 2.0 | 5 votes |
private static Bootstrap initBootStrap() { Bootstrap cb = new Bootstrap(); Verify.verifyNotNull(cb); cb.group(ApplicationRuntime.FTDC_LOOP_GROUP); cb.channel(NioSocketChannel.class); cb.option(ChannelOption.SO_KEEPALIVE, false); return cb; }
Example 9
Source File: RequestResponseCloseHandlerTest.java From servicetalk with Apache License 2.0 | 5 votes |
private SocketChannel connectClient(InetSocketAddress address) { EventLoopAwareNettyIoExecutor eventLoopAwareNettyIoExecutor = toEventLoopAwareNettyIoExecutor(C_CTX.ioExecutor()); EventLoop loop = eventLoopAwareNettyIoExecutor.eventLoopGroup().next(); Bootstrap bs = new Bootstrap(); bs.group(loop); bs.channel(socketChannel(loop, InetSocketAddress.class)); bs.handler(new ChannelInitializer() { @Override protected void initChannel(final Channel ch) { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) { LOGGER.debug("Client Evt: {}", evt.getClass().getSimpleName()); if (evt == ChannelInputShutdownEvent.INSTANCE) { clientInputShutdownLatch.countDown(); } else if (evt == ChannelInputShutdownReadComplete.INSTANCE) { clientInputShutdownReadCompleteLatch.countDown(); } else if (evt == ChannelOutputShutdownEvent.INSTANCE) { clientOutputShutdownLatch.countDown(); } release(evt); } }); } }); bs.option(AUTO_READ, true); bs.option(ALLOW_HALF_CLOSURE, true); bs.option(AUTO_CLOSE, false); return (SocketChannel) bs.connect(address).syncUninterruptibly().channel(); }
Example 10
Source File: Netty4Transport.java From crate with Apache License 2.0 | 5 votes |
private Bootstrap createClientBootstrap() { final Bootstrap bootstrap = new Bootstrap(); if (Epoll.isAvailable()) { bootstrap.group(new EpollEventLoopGroup(workerCount, daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX))); bootstrap.channel(EpollSocketChannel.class); } else { bootstrap.group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX))); bootstrap.channel(NioSocketChannel.class); } bootstrap.option(ChannelOption.TCP_NODELAY, TransportSettings.TCP_NO_DELAY.get(settings)); bootstrap.option(ChannelOption.SO_KEEPALIVE, TransportSettings.TCP_KEEP_ALIVE.get(settings)); final ByteSizeValue tcpSendBufferSize = TransportSettings.TCP_SEND_BUFFER_SIZE.get(settings); if (tcpSendBufferSize.getBytes() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.getBytes())); } final ByteSizeValue tcpReceiveBufferSize = TransportSettings.TCP_RECEIVE_BUFFER_SIZE.get(settings); if (tcpReceiveBufferSize.getBytes() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.getBytes())); } bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); final boolean reuseAddress = TransportSettings.TCP_REUSE_ADDRESS.get(settings); bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); return bootstrap; }
Example 11
Source File: BGPDispatcherImpl.java From bgpcep with Eclipse Public License 1.0 | 5 votes |
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 12
Source File: BmpDispatcherUtil.java From bgpcep with Eclipse Public License 1.0 | 5 votes |
public static Bootstrap createClientBootstrap(final @NonNull BmpSessionFactory sessionFactory, final @NonNull BmpHandlerFactory hf, final @NonNull CreateChannel createChannel, final @NonNull BmpSessionListenerFactory slf, final @NonNull InetSocketAddress remoteAddress, final @Nullable SocketAddress localAddress, final @NonNull EventLoopGroup workerGroup, final int connectTimeout, final @NonNull KeyMapping keys, boolean reuseAddress, boolean tryEpollSocket) { final Bootstrap bootstrap = new Bootstrap(); bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); bootstrap.group(workerGroup); bootstrap.handler(createChannel.create(sessionFactory, hf, slf)); if (localAddress != null) { bootstrap.localAddress(localAddress); } bootstrap.remoteAddress(remoteAddress); if (!tryEpollSocket) { bootstrap.channel(NioSocketChannel.class); } else { if (Epoll.isAvailable()) { bootstrap.channel(EpollSocketChannel.class); } else { bootstrap.channel(NioSocketChannel.class); } if (!keys.isEmpty()) { if (Epoll.isAvailable()) { bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys); } else { throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause()); } } } return bootstrap; }
Example 13
Source File: IpmiClientImpl.java From ipmi4j with Apache License 2.0 | 5 votes |
@Override public void start() throws IOException, InterruptedException { IpmiChannelType mode = getChannelType(); ThreadFactory factory = new DefaultThreadFactory("ipmi-client"); EventLoopGroup group = mode.newEventLoopGroup(factory); Bootstrap b = new Bootstrap(); b.group(group); b.channel(mode.getChannelType()); b.handler(new IpmiPipelineInitializer(sharedHandlers, new IpmiClientHandler(this))); channel = b.bind(0).sync().channel(); }
Example 14
Source File: DhcpServer.java From dhcp4j with Apache License 2.0 | 5 votes |
@PostConstruct public void start() throws IOException, InterruptedException { super.start(); ThreadFactory factory = new DefaultThreadFactory("dhcp-server"); EventLoopGroup group = new NioEventLoopGroup(0, factory); Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioDatagramChannel.class); b.option(ChannelOption.SO_BROADCAST, true); b.handler(new DhcpHandler(service, this)); channel = b.bind(port).sync().channel(); }
Example 15
Source File: ProxyServer.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private 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 16
Source File: AbstractFrameTransport.java From qpid-broker-j with Apache License 2.0 | 5 votes |
public AbstractFrameTransport<I> connect() { try { Bootstrap b = new Bootstrap(); b.group(_workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); buildInputOutputPipeline(pipeline); } }); _channel = b.connect(_brokerAddress).sync().channel(); _channel.closeFuture().addListener(future -> { _channelClosedSeen = true; _queue.add(CHANNEL_CLOSED_RESPONSE); }); } catch (InterruptedException e) { throw new RuntimeException(e); } return this; }
Example 17
Source File: ProxyServer.java From xio with Apache License 2.0 | 5 votes |
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 18
Source File: NettyServerManager.java From anetty_client with Apache License 2.0 | 4 votes |
/** * 连接方法 * * @param host * @param port * @throws Exception */ @SuppressWarnings("rawtypes") public void connect(final String host, final int port, final INettyHandlerListener connectionListener) throws Exception { Log.i(getClass().getName(), "connect come in!connectState=" + connectState); if (isConnected() || connectState == CONNECT_PROCESSORING) { // 連接成功 停止重连 NettyAlarmManager.stopReconnection(); return; } Log.i(getClass().getName(), "connect come in!CONNECT_PROCESSORING!"); connectState = CONNECT_PROCESSORING; mHost = host; mPort = port; System.setProperty("java.net.preferIPv4Stack", "true"); System.setProperty("java.net.preferIPv6Addresses", "false"); ChannelFuture channelFuture = null; group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.TCP_NODELAY, true); b.remoteAddress(new InetSocketAddress(mHost, mPort)); // 有连接到达时会创建一个channel final ExtensionRegistry registry = ExtensionRegistry.newInstance(); CommandProtoc.registerAllExtensions(registry); b.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder()); pipeline.addLast("protobufDecoder", new ProtobufDecoder(CommandProtoc.PushMessage.getDefaultInstance(), registry)); pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast("protobufEncoder", new ProtobufEncoder()); pipeline.addLast(new PushMessageHandler(connectionManager, mNettyProcessorHandler)); } }); channelFuture = b.connect().sync(); channelFuture.addListener(new ChannelFutureListener() { @SuppressWarnings("unchecked") public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { SocketAddress sa = future.channel().remoteAddress(); if(sa!=null){ Log.i(getClass().getName(), "netty server connected success! host:" + sa); // 連接成功 connectState = CONNECT_SUCCESS; if (connectionListener != null) { connectionListener.callback(null); } // 启动心跳程序 NettyAlarmManager.startHeart(mContext); // 連接成功 停止重连 NettyAlarmManager.stopReconnection(); }else{ Log.i(getClass().getName(), "netty server connected failed! host:" + sa); // 連接失敗 connectState = CONNECT_FAILED; // 連接 失敗 啟動重連 future.cause().printStackTrace(); future.channel().close(); } } else { Log.i(getClass().getName(), "netty server attemp failed! host:" + future.channel().remoteAddress()); // 連接失敗 connectState = CONNECT_FAILED; // 連接 失敗 啟動重連 future.cause().printStackTrace(); future.channel().close(); // NettyAlarmManager.startReconnection(mContext); // if (mNetworkCallback != null) { // mNetworkCallback.connectFailed(); // } } } }); // Wait until the connection is closed. // channelFuture.channel().closeFuture().sync(); } catch (Exception e) { Log.i(getClass().getName(), e.getMessage()); connectState = CONNECT_EXCEPTION; // 连接关闭后启动重连 NettyAlarmManager.startReconnection(mContext); } finally { Log.i(getClass().getName(), "connect finally!connectState=" + connectState); disconnect(channelFuture); } }
Example 19
Source File: ProxyClientHandler.java From karate with MIT License | 4 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { boolean isConnect = HttpMethod.CONNECT.equals(request.method()); ProxyContext pc = new ProxyContext(request, isConnect); // if ssl CONNECT, always create new remote pipeline if (remoteHandler == null && !isConnect) { remoteHandler = REMOTE_HANDLERS.get(pc.hostColonPort); } if (remoteHandler != null) { remoteHandler.send(request); return; } if (logger.isTraceEnabled()) { logger.trace(">> init: {} - {}", pc, request); } Bootstrap b = new Bootstrap(); b.group(new NioEventLoopGroup(4)); b.channel(NioSocketChannel.class); b.handler(new ChannelInitializer() { @Override protected void initChannel(Channel remoteChannel) throws Exception { ChannelPipeline p = remoteChannel.pipeline(); if (isConnect) { SSLContext sslContext = NettyUtils.getSslContext(null); SSLEngine remoteSslEngine = sslContext.createSSLEngine(pc.host, pc.port); remoteSslEngine.setUseClientMode(true); remoteSslEngine.setNeedClientAuth(false); SslHandler remoteSslHandler = new SslHandler(remoteSslEngine); p.addLast(remoteSslHandler); remoteSslHandler.handshakeFuture().addListener(rhf -> { if (logger.isTraceEnabled()) { logger.trace("** ssl: server handshake done: {}", remoteChannel); } SSLEngine clientSslEngine = sslContext.createSSLEngine(); clientSslEngine.setUseClientMode(false); clientSslEngine.setNeedClientAuth(false); SslHandler clientSslHandler = new SslHandler(clientSslEngine); HttpResponse response = NettyUtils.connectionEstablished(); response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); clientChannel.eventLoop().execute(() -> { clientChannel.writeAndFlush(response); clientChannel.pipeline().addFirst(clientSslHandler); }); clientSslHandler.handshakeFuture().addListener(chf -> { if (logger.isTraceEnabled()) { logger.trace("** ssl: client handshake done: {}", clientChannel); } unlockAndProceed(); }); lockAndWait(); }); } p.addLast(new HttpClientCodec()); p.addLast(new HttpContentDecompressor()); p.addLast(new HttpObjectAggregator(1048576)); remoteHandler = new ProxyRemoteHandler(pc, ProxyClientHandler.this, isConnect ? null : request); REMOTE_HANDLERS.put(pc.hostColonPort, remoteHandler); p.addLast(remoteHandler); if (logger.isTraceEnabled()) { logger.trace("updated remote handlers: {}", REMOTE_HANDLERS); } } }); ChannelFuture cf = b.connect(pc.host, pc.port); cf.addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { if (logger.isTraceEnabled()) { logger.trace("** ready: {} - {}", pc, cf.channel()); } } else { NettyUtils.flushAndClose(clientChannel); } }); if (!isConnect) { lockAndWait(); } }
Example 20
Source File: MqttClientImpl.java From smartacus-mqtt-broker with Apache License 2.0 | 4 votes |
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; }