本文整理匯總了Java中io.netty.bootstrap.Bootstrap.connect方法的典型用法代碼示例。如果您正苦於以下問題:Java Bootstrap.connect方法的具體用法?Java Bootstrap.connect怎麽用?Java Bootstrap.connect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類io.netty.bootstrap.Bootstrap
的用法示例。
在下文中一共展示了Bootstrap.connect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: connectAsync
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
ethereumListener.trace("Connecting to: " + host + ":" + port);
EthereumChannelInitializer ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, remoteId);
ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());
b.remoteAddress(host, port);
b.handler(ethereumChannelInitializer);
// Start the client.
return b.connect();
}
示例2: connectAsync
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
ethereumListener.trace("Connecting to: " + host + ":" + port);
EthereumChannelInitializer ethereumChannelInitializer = ethereumChannelInitializerFactory.newInstance(remoteId);
ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());
b.remoteAddress(host, port);
b.handler(ethereumChannelInitializer);
// Start the client.
return b.connect();
}
示例3: EchoClient
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
public EchoClient(String host, int port) {
EventLoopGroup worker = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(worker)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) {
socketChannel.pipeline()
.addLast(new StringDecoder())
.addLast(new StringEncoder())
.addLast(ech);
}
});
b.connect(host, port);
}
示例4: channelActive
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
final Channel inboundChannel = ctx.channel();
// Start the connection attempt.
Bootstrap b = new Bootstrap();
b.group(inboundChannel.eventLoop())
.channel(ctx.channel().getClass())
.handler(new CardeaServerBackendHandler(inboundChannel))
.option(ChannelOption.AUTO_READ, false);
ChannelFuture f = b.connect(host, port);
outboundChannel = f.channel();
f.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
// connection complete start to read first data
inboundChannel.read();
} else {
// Close the connection if the connection attempt has failed.
inboundChannel.close();
}
});
}
示例5: connect
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public void connect() {
checkState(channel == null, "channel already initialized");
try {
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init((KeyStore) null);
final SslContext sslContext = SslContextBuilder.forClient()
.trustManager(trustFactory).build();
Bootstrap bootstrap = new Bootstrap();
final int port = uri.getPort() != -1 ? uri.getPort() : DEFAULT_WSS_PORT;
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
p.addLast(
new HttpClientCodec(),
// Set the max size for the HTTP responses. This only applies to the WebSocket
// handshake response from the server.
new HttpObjectAggregator(32 * 1024),
channelHandler);
}
});
ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), port);
this.channel = channelFuture.channel();
channelFuture.addListener(
new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
eventHandler.onError(future.cause());
}
}
}
);
} catch (Exception e) {
eventHandler.onError(e);
}
}
示例6: connect
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public Connection connect(Address address, Consumer<TransportChannel> successEvent) {
Bootstrap bootstrap = bootstrap();
final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(), address.getPort());
bootstrap.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline()
.addLast(new Encoder(serializer))
.addLast(new Decoder(serializer))
.addLast(new ConsumerHandler());
}
});
ChannelFuture connectChannelFuture = bootstrap.connect(socketAddress);
connectChannelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
TransportChannel transportChannel = NettyChannel.getInstance(future.channel());
successEvent.accept(transportChannel);
}
}
});
return new NettyConnection(connectChannelFuture);
}
示例7: channelRead0
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest msg) throws Exception {
final Channel inboundChannel = ctx.channel();
String host = msg.headers().get("Host");
int port = 80;
String pattern = "(http://|https://)?([^:]+)(:[\\d]+)?";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(host);
if (m.find()) {
host = m.group(2);
port = (m.group(3) == null) ? 80 : Integer.parseInt(m.group(3).substring(1));
}
Bootstrap b = new Bootstrap();
b.group(inboundChannel.eventLoop()) // use inboundChannel thread
.channel(ctx.channel().getClass())
.handler(new BackendHandlerInitializer(inboundChannel));
ChannelFuture f = b.connect(host, port);
outboundChannel = f.channel();
msg.retain();
f.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
outboundChannel.writeAndFlush(msg);
} else {
inboundChannel.close();
}
}
});
}
示例8: connect
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
ChannelFuture connect(ChannelHandler... handlers) {
SslContext sslCtx;
try {
sslCtx = SslContextBuilder
.forClient()
.trustManager(getClass().getResourceAsStream("cloudwall/exchange/gdax/gdax.pem"))
.build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(sslCtx.newHandler(ch.alloc()));
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new HttpObjectAggregator(10485760));
p.addLast(handlers);
}
});
return bootstrap.connect(host, port);
}
示例9: start
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public boolean start() {
boolean result = false;
do {
TcpRouteDefinition route = definition.getRoute();
if(null == route) {
break;
}
if(route.getAddress() == null || route.getAddress().isEmpty()) {
break;
}
if(route.getPort() == -1) {
break;
}
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(inbound.getClass());
bootstrap.group(inbound.eventLoop());
bootstrap.handler(new TcpProxyClientChannelInitializer(definition, this));
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.option(ChannelOption.AUTO_READ, false);
ChannelFuture future = bootstrap.connect(route.getAddress(), route.getPort());
//forwarder = future.sync().channel();
outbound = future.channel();
future.addListener(listener);
} catch (Exception e) {
log.error("Failed starting tcp proxy client.", e);
outbound = null;
break;
}
result = true;
} while (false);
return result;
}
示例10: start
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public boolean start() {
boolean result = false;
do {
List<HttpRouteDefinition> routes = definition.getRoutes();
for(HttpRouteDefinition route: routes) {
if (null == route) {
break;
}
if (route.getInputUrl() == null || route.getInputUrl().isEmpty()) {
break;
}
if (route.getScheme().equals(null)) {
break;
}
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(inbound.getClass());
bootstrap.group(inbound.eventLoop());
bootstrap.handler(new HttpProxyClientChannelInitializer(definition, this));
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.option(ChannelOption.AUTO_READ, false);
ChannelFuture future = bootstrap.connect(route.getHost(), route.getPort());
//forwarder = future.sync().channel();
outbound = future.channel();
future.addListener(listener);
} catch (Exception e) {
log.error("Failed starting http proxy client.", e);
outbound = null;
break;
}
}
result = true;
} while (false);
return result;
}
示例11: main
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
public static void main(String[] args) throws InterruptedException, NoSuchAlgorithmException {
InetSocketAddress addr = new InetSocketAddress(GOOGLE_SERVER_HOST, GOOGLE_SERVER_PORT);
System.out.printf("Sending request to %s\n", addr);
// Below is Netty boilerplate for setting-up an event loop and registering a handler
NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap()
.group(group)
.remoteAddress(addr)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
protected void initChannel(NioDatagramChannel ch) throws Exception {
ch.pipeline()
.addLast(new ReadTimeoutHandler(5))
.addLast(new RequestHandler(addr));
}
});
ChannelFuture connectFuture = bootstrap.connect();
connectFuture.addListener(fut -> {
if (!fut.isSuccess()) {
System.out.println("Connect fail:");
System.out.println(fut.cause().getMessage());
}
});
connectFuture.channel().closeFuture().sync();
group.shutdownGracefully();
}
示例12: Bootstrap
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public void channelRead0
(final ChannelHandlerContext ctx, final HttpRequest req) {
uri = req.getUri();
final Channel client = ctx.channel();
Bootstrap proxiedServer = new Bootstrap()
.group(client.eventLoop())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
}
});
ChannelFuture f = proxiedServer.connect(host);
proxiedChannel = f.channel();
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ctx.channel().pipeline().remove(HttpResponseEncoder.class);
HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
req.getMethod(), req.getUri());
newReq.headers().add(req.headers());
newReq.headers().set(CONNECTION, Values.CLOSE);
future.channel().writeAndFlush(newReq);
} else {
DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
INTERNAL_SERVER_ERROR);
resp.headers().set(CONNECTION, Values.CLOSE);
LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
client.close();
}
}
});
}
示例13: makeObject
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public Connection makeObject(Endpoint ep) throws Exception {
Bootstrap bootstrap = new Bootstrap();
bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024);
bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10 * 32 * 1024);
bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
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.option(ChannelOption.SO_KEEPALIVE, true);
if (enableNettyTls) {
bootstrap.handler(new SslClientCommunicationChannelInitializer());
} else {
bootstrap.handler(new OnosCommunicationChannelInitializer());
}
// Start the client.
CompletableFuture<Channel> retFuture = new CompletableFuture<>();
ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port());
f.addListener(future -> {
if (future.isSuccess()) {
retFuture.complete(f.channel());
} else {
retFuture.completeExceptionally(future.cause());
}
});
log.debug("Established a new connection to {}", ep);
return new Connection(retFuture);
}
示例14: handleProxyData
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
private void handleProxyData(Channel channel, Object msg, boolean isHttp)
throws Exception {
if (cf == null) {
if (isHttp && !(msg instanceof HttpRequest)) { //connection異常 還有HttpContent進來,不轉發
return;
}
ProxyHandler proxyHandler = ProxyHandleFactory.build(proxyConfig);
/*
添加SSL client hello的Server Name Indication extension(SNI擴展)
有些服務器對於client hello不帶SNI擴展時會直接返回Received fatal alert: handshake_failure(握手錯誤)
例如:https://cdn.mdn.mozilla.net/static/img/favicon32.7f3da72dcea1.png
*/
RequestProto requestProto = new RequestProto(host, port, isSsl);
ChannelInitializer channelInitializer =
isHttp ? new HttpProxyInitializer(channel, requestProto, proxyHandler)
: new TunnelProxyInitializer(channel, proxyHandler);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(serverConfig.getLoopGroup()) // 注冊線程池
.channel(NioSocketChannel.class) // 使用NioSocketChannel來作為連接用的channel類
.handler(channelInitializer);
if (proxyConfig != null) {
//代理服務器解析DNS和連接
bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
}
requestList = new LinkedList();
cf = bootstrap.connect(host, port);
cf.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
future.channel().writeAndFlush(msg);
synchronized (requestList) {
requestList.forEach((obj) -> future.channel().write(obj));
requestList.clear();
isConnect = true;
}
} else {
future.channel().close();
channel.close();
}
});
} else {
synchronized (requestList) {
if (isConnect) {
cf.channel().writeAndFlush(msg);
} else {
requestList.add(msg);
}
}
}
}
示例15: start
import io.netty.bootstrap.Bootstrap; //導入方法依賴的package包/類
@Override
public synchronized void start() {
if (isStarting) {
return;
}
isStarting = true;
nettyDistributeService.loadTxServer();
String host = Constants.txServer.getHost();
int port = Constants.txServer.getPort();
final int heart = Constants.txServer.getHeart();
int delay = Constants.txServer.getDelay();
transactionHandler = new TransactionHandler(this, delay);
workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("timeout", new IdleStateHandler(heart, heart, heart, TimeUnit.SECONDS));
ch.pipeline().addLast(new LengthFieldPrepender(4, false));
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
ch.pipeline().addLast(transactionHandler);
}
});
// Start the client.
logger.info("連接manager-socket服務-> host:" + host + ",port:" + port);
ChannelFuture future = b.connect(host, port); // (5)
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if (!channelFuture.isSuccess()) {
channelFuture.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
isStarting = false;
start();
}
}, 5, TimeUnit.SECONDS);
}
}
});
} catch (Exception e) {
e.printStackTrace();
// isStarting = false;
//
// //斷開重新連接機製
// close();
//
// if (e instanceof ConnectTimeoutException) {
// start();
// }
}
}