public final void run(final String host, final int port, final ChannelHandler pipelineFactory) { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(host, port) .option(ChannelOption.TCP_NODELAY, true) .handler(pipelineFactory); try { Channel channel = bootstrap.connect().sync().channel(); ChannelFuture future = channel.closeFuture().sync(); future.addListener(ChannelFutureListener.CLOSE); } catch (InterruptedException e) { throw new MocoException(e); } finally { group.shutdownGracefully(); } } }
private Bootstrap buildBootstrap(URI uri, boolean isSecure) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { configureChannel(channel.config()); ChannelPipeline pipeline = channel.pipeline(); if (isSecure) { Assert.notNull(sslContext, "sslContext should not be null"); pipeline.addLast(sslContext.newHandler(channel.alloc(), uri.getHost(), uri.getPort())); } pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(maxResponseSize)); if (readTimeout > 0) { pipeline.addLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS)); } } }); return bootstrap; }
private void groupsEpoll(final Bootstrap bootstrap) { bootstrap.group(workerGroup) .channel(EpollSocketChannel.class) .option(EpollChannelOption.TCP_CORK, true) .option(EpollChannelOption.SO_KEEPALIVE, true) .option(EpollChannelOption.SO_BACKLOG, 128) .option(EpollChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); }
public EventLoopGroup kqueueGroup() { EventLoopGroup nioEventLoopGroup = new KQueueEventLoopGroup(0, createThreadFactory()); bootstrap.group(nioEventLoopGroup).channel(KQueueDomainSocketChannel.class) .handler(new ChannelInitializer<KQueueDomainSocketChannel>() { @Override protected void initChannel(final KQueueDomainSocketChannel channel) throws Exception { channel.pipeline().addLast(new HttpClientCodec()); channel.pipeline().addLast(new HttpContentDecompressor()); } }); return nioEventLoopGroup; }
URI uri = URI.create(url); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); new Bootstrap() .group(eventLoop) .resolver(resolverGroup) .channel(GlowServer.EPOLL ? EpollSocketChannel.class : GlowServer.KQUEUE ? KQueueSocketChannel.class : NioSocketChannel.class) .handler(new HttpChannelInitializer(sslCtx, callback)) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) .connect(InetSocketAddress.createUnresolved(host, port)) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery()); HttpMethod.GET, path); request.headers().set(HttpHeaderNames.HOST, host); future.channel().writeAndFlush(request); } else { callback.error(future.cause());
URI uri = new URI(url); String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; WebSocketVersion.V13, null, true, httpHeaders), callback); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { channel = b.connect(uri.getHost(), port).sync().channel(); isDone = handler.handshakeFuture().sync().isSuccess(); } catch (Exception e) { LOGGER.debug("Handshake unsuccessful : " + e.getMessage(), e); group.shutdownGracefully(); return false;
port = uri.getPort(); EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { bootstrap.resolver(NoopAddressResolverGroup.INSTANCE); Channel ch = bootstrap.connect(host, port).sync().channel(); if (httpProxyHandler != null) { ch.writeAndFlush(request).get(); ch.closeFuture().sync().get(); Throwable exception = handler.exception; if (exception != null) { group.shutdownGracefully(0, 10, SECONDS).get();
public void run(int port) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ChineseProverbServerHandler()); b.bind(port).sync().channel().closeFuture().await(); } finally { group.shutdownGracefully(); } }
InetSocketAddress remoteDestination = new InetSocketAddress(IPV6Util.stripBracketsAndZoneID(host), port); SocketAddress localDestination; if (localAddress != null) { localDestination = new InetSocketAddress(localAddress, localPort); } else { localDestination = new InetSocketAddress(localPort); future = bootstrap.connect(remoteDestination, localDestination); } else { future = bootstrap.connect(remoteDestination); future.awaitUninterruptibly(); URI uri = new URI(scheme, null, ipv6Host, port, null, null, null); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaderNames.HOST, ipv6Host); request.headers().set(HttpHeaderNames.UPGRADE, ACTIVEMQ_REMOTING);
String host = requestUri.getHost(); int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80; Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ClientProperties.CONNECT_TIMEOUT, 0); if (connectTimeout > 0) { b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); final Channel ch = b.connect(host, port).sync().channel(); ch.closeFuture().addListener(closeListener);
@Override public void request(RequestContext context) throws Exception { URI uri = new URI(context.request.uri()); String host = context.host = uri.getHost(); int port = uri.getPort() == -1 ? 80 : uri.getPort(); final long startCreate = System.currentTimeMillis(); LOGGER.debug("create new channel, host={}", host); ChannelFuture f = b.connect(host, port); f.addListener((ChannelFutureListener) future -> { LOGGER.debug("create new channel cost={}", (System.currentTimeMillis() - startCreate)); if (future.isSuccess()) {//3.1.把请求写到http server writeRequest(future.channel(), context); } else {//3.2如果链接创建失败,直接返回客户端网关超时 context.tryDone();
/** * Listing 8.3 Incompatible Channel and EventLoopGroup * */ public void bootstrap() { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(OioSocketChannel.class) .handler(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0( ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception { System.out.println("Received data"); } }); ChannelFuture future = bootstrap.connect( new InetSocketAddress("www.manning.com", 80)); future.syncUninterruptibly(); } }
EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0( bootstrap.connect( new InetSocketAddress("www.manning.com", 80)); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture)
public ChannelFuture connect(final EventLoop eventLoop, String host, final int port, CurrentPassport passport) { Class socketChannelClass; if (Server.USE_EPOLL.get()) { socketChannelClass = EpollSocketChannel.class; } else { socketChannelClass = NioSocketChannel.class; } SocketAddress socketAddress = new InetSocketAddress(host, port); final Bootstrap bootstrap = new Bootstrap() .channel(socketChannelClass) .handler(channelInitializer) .group(eventLoop) .attr(CurrentPassport.CHANNEL_ATTR, passport) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connPoolConfig.getConnectTimeout()) .option(ChannelOption.SO_KEEPALIVE, connPoolConfig.getTcpKeepAlive()) .option(ChannelOption.TCP_NODELAY, connPoolConfig.getTcpNoDelay()) .option(ChannelOption.SO_SNDBUF, connPoolConfig.getTcpSendBufferSize()) .option(ChannelOption.SO_RCVBUF, connPoolConfig.getTcpReceiveBufferSize()) .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, connPoolConfig.getNettyWriteBufferHighWaterMark()) .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, connPoolConfig.getNettyWriteBufferLowWaterMark()) .option(ChannelOption.AUTO_READ, connPoolConfig.getNettyAutoRead()) .remoteAddress(socketAddress); ZuulBootstrap zuulBootstrap = new ZuulBootstrap(bootstrap); if (!zuulBootstrap.getResolver(eventLoop).isResolved(socketAddress)) { LOGGER.warn("NettyClientConnectionFactory got an unresolved server address, host: " + host + ", port: " + port); unresolvedDiscoveryHost.increment(); } return bootstrap.connect(); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class).handler( new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0( ChannelHandlerContext ctx, ByteBuf in) throws Exception { System.out.println("Received data"); } }); bootstrap.group(ctx.channel().eventLoop()); connectFuture = bootstrap.connect( new InetSocketAddress("www.manning.com", 80)); }
final THttp2ClientInitializer initHandler = new THttp2ClientInitializer(); final Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.handler(initHandler); ch = b.connect(host, port).syncUninterruptibly().channel(); final THttp2ClientHandler handler = initHandler.clientHandler; Unpooled.wrappedBuffer(out.getArray(), 0, out.length())); request.headers().add(HttpHeaderNames.HOST, host); request.headers().set(ExtensionHeaderNames.SCHEME.text(), uri.getScheme()); request.headers().add(defaultHeaders); ch.writeAndFlush(request).sync(); } finally { if (ch != null) { ch.close();
@Override public DuplexChannel connect(Bootstrap bootstrap) throws InterruptedException { DockerClientConfig dockerClientConfig = getDockerClientConfig(); String host = dockerClientConfig.getDockerHost().getHost(); int port = dockerClientConfig.getDockerHost().getPort(); if (port == -1) { throw new RuntimeException("no port configured for " + host); } DuplexChannel channel = (DuplexChannel) bootstrap.connect(host, port).sync().channel(); final SslHandler ssl = initSsl(dockerClientConfig); if (ssl != null) { channel.pipeline().addFirst(ssl); } return channel; }
@Override protected ListenableFuture<ClientHttpResponse> executeInternal(final HttpHeaders headers) throws IOException { final SettableListenableFuture<ClientHttpResponse> responseFuture = new SettableListenableFuture<>(); ChannelFutureListener connectionListener = future -> { if (future.isSuccess()) { Channel channel = future.channel(); channel.pipeline().addLast(new RequestExecuteHandler(responseFuture)); FullHttpRequest nettyRequest = createFullHttpRequest(headers); channel.writeAndFlush(nettyRequest); } else { responseFuture.setException(future.cause()); } }; this.bootstrap.connect(this.uri.getHost(), getPort(this.uri)).addListener(connectionListener); return responseFuture; }
/** * Connect a {@link Channel} to the remote peer. */ public ChannelFuture connect(InetAddress inetHost, int inetPort) { return connect(new InetSocketAddress(inetHost, inetPort)); }
private <T> Flowable<T> connectWebSocket(URI uri, MutableHttpRequest<?> request, Class<T> clientEndpointType, WebSocketBean<T> webSocketBean) { Bootstrap bootstrap = this.bootstrap.clone(); if (webSocketBean == null) { webSocketBean = webSocketRegistry.getWebSocket(clientEndpointType); int maxFramePayloadLength = finalWebSocketBean.messageMethod().flatMap(m -> m.getValue(OnMessage.class, "maxPayloadLength", Integer.class)).orElse(65536); bootstrap.remoteAddress(uri.getHost(), uri.getPort()); bootstrap.handler(new HttpClientInitializer( sslContext, uri.getHost(), uri.getPort(), false, bootstrap.connect().addListener((ChannelFutureListener) future -> { if (!future.isSuccess()) { emitter.onError(future.cause());