本文整理了Java中io.netty.bootstrap.Bootstrap
类的一些代码示例,展示了Bootstrap
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Bootstrap
类的具体详情如下:
包路径:io.netty.bootstrap.Bootstrap
类名称:Bootstrap
[英]A Bootstrap that makes it easy to bootstrap a Channel to use for clients.
The #bind() methods are useful in combination with connectionless transports such as datagram (UDP). For regular TCP connections, please use the provided #connect() methods.
[中]一种引导程序,可轻松引导通道供客户端使用。
#bind()方法与数据报(UDP)等无连接传输结合使用非常有用。对于常规TCP连接,请使用提供的#connect()方法。
代码示例来源:origin: dreamhead/moco
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();
}
}
}
代码示例来源:origin: spring-projects/spring-framework
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;
}
代码示例来源:origin: apache/incubator-shardingsphere
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);
}
代码示例来源:origin: testcontainers/testcontainers-java
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;
}
代码示例来源:origin: GlowstoneMC/Glowstone
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());
代码示例来源:origin: ballerina-platform/ballerina-lang
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;
代码示例来源:origin: glowroot/glowroot
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();
代码示例来源:origin: wuyinxian124/nettybook2
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();
}
}
代码示例来源:origin: wildfly/wildfly
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);
代码示例来源:origin: jersey/jersey
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);
代码示例来源:origin: mpusher/mpush
@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();
代码示例来源:origin: normanmaurer/netty-in-action
/**
* 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();
}
}
代码示例来源:origin: normanmaurer/netty-in-action
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)
代码示例来源:origin: Netflix/zuul
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();
}
代码示例来源:origin: normanmaurer/netty-in-action
@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));
}
代码示例来源:origin: line/armeria
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();
代码示例来源:origin: testcontainers/testcontainers-java
@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;
}
代码示例来源:origin: spring-projects/spring-framework
@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;
}
代码示例来源:origin: netty/netty
/**
* Connect a {@link Channel} to the remote peer.
*/
public ChannelFuture connect(InetAddress inetHost, int inetPort) {
return connect(new InetSocketAddress(inetHost, inetPort));
}
代码示例来源:origin: micronaut-projects/micronaut-core
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());
内容来源于网络,如有侵权,请联系作者删除!