use of io.netty.bootstrap.Bootstrap in project jgnash by ccavanaugh.
the class AttachmentTransferClient method connectToServer.
/**
* Starts the connection with the lock server.
*
* @param host remote host
* @param port connection port
* @param password connection password
* @return {@code true} if successful
*/
boolean connectToServer(final String host, final int port, final char[] password) {
boolean result = false;
// If a password has been specified, create an EncryptionManager
if (password != null && password.length > 0) {
encryptionManager = new EncryptionManager(password);
}
final Bootstrap bootstrap = new Bootstrap();
eventLoopGroup = new NioEventLoopGroup();
transferHandler = new NettyTransferHandler(tempDirectory, encryptionManager);
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new Initializer()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConnectionFactory.getConnectionTimeout() * 1000).option(ChannelOption.SO_KEEPALIVE, true);
try {
// Start the connection attempt.
channel = bootstrap.connect(host, port).sync().channel();
result = true;
logger.info("Connection made with File Transfer Server");
} catch (final InterruptedException e) {
logger.log(Level.SEVERE, "Failed to connect to the File Transfer Server", e);
disconnectFromServer();
}
return result;
}
use of io.netty.bootstrap.Bootstrap in project jgnash by ccavanaugh.
the class DistributedLockManager method connectToServer.
/**
* Starts the connection with the lock server.
*
* @param password connection password
* @return {@code true} if successful
*/
public boolean connectToServer(final char[] password) {
boolean result = false;
// If a password has been specified, create an EncryptionManager
if (password != null && password.length > 0) {
encryptionManager = new EncryptionManager(password);
}
final Bootstrap bootstrap = new Bootstrap();
eventLoopGroup = new NioEventLoopGroup();
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new Initializer()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConnectionFactory.getConnectionTimeout() * 1000).option(ChannelOption.SO_KEEPALIVE, true);
try {
// Start the connection attempt.
channel = bootstrap.connect(host, port).sync().channel();
// send this channels uuid
channel.writeAndFlush(encrypt(UUID_PREFIX + uuid) + EOL_DELIMITER).sync();
result = true;
logger.info("Connection made with Distributed Lock Server");
} catch (final InterruptedException e) {
logger.log(Level.SEVERE, "Failed to connect to Distributed Lock Server", e);
disconnectFromServer();
}
return result;
}
use of io.netty.bootstrap.Bootstrap in project flink by apache.
the class NettyClient method init.
void init(final NettyProtocol protocol, NettyBufferPool nettyBufferPool) throws IOException {
checkState(bootstrap == null, "Netty client has already been initialized.");
this.protocol = protocol;
long start = System.currentTimeMillis();
bootstrap = new Bootstrap();
switch(config.getTransportType()) {
case NIO:
initNioBootstrap();
break;
case EPOLL:
initEpollBootstrap();
break;
case AUTO:
if (Epoll.isAvailable()) {
initEpollBootstrap();
LOG.info("Transport type 'auto': using EPOLL.");
} else {
initNioBootstrap();
LOG.info("Transport type 'auto': using NIO.");
}
}
// --------------------------------------------------------------------
// Configuration
// --------------------------------------------------------------------
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
// Timeout for new connections
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getClientConnectTimeoutSeconds() * 1000);
// Pooled allocator for Netty's ByteBuf instances
bootstrap.option(ChannelOption.ALLOCATOR, nettyBufferPool);
// Receive and send buffer size
int receiveAndSendBufferSize = config.getSendAndReceiveBufferSize();
if (receiveAndSendBufferSize > 0) {
bootstrap.option(ChannelOption.SO_SNDBUF, receiveAndSendBufferSize);
bootstrap.option(ChannelOption.SO_RCVBUF, receiveAndSendBufferSize);
}
try {
clientSSLContext = config.createClientSSLContext();
} catch (Exception e) {
throw new IOException("Failed to initialize SSL Context for the Netty client", e);
}
long end = System.currentTimeMillis();
LOG.info("Successful initialization (took {} ms).", (end - start));
}
use of io.netty.bootstrap.Bootstrap in project apn-proxy by apn-proxy.
the class ApnProxyUserAgentTunnelHandler method channelRead.
@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
final HttpRequest httpRequest = (HttpRequest) msg;
//Channel uaChannel = uaChannelCtx.channel();
// connect remote
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).option(ChannelOption.AUTO_READ, false).handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel()));
final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel().attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();
// set local address
if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
bootstrap.localAddress(new InetSocketAddress((ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
}
bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(final ChannelFuture future1) throws Exception {
if (future1.isSuccess()) {
if (apnProxyRemote.isAppleyRemoteRule()) {
uaChannelCtx.pipeline().remove("codec");
uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);
// add relay handler
uaChannelCtx.pipeline().addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel()));
future1.channel().writeAndFlush(Unpooled.copiedBuffer(constructConnectRequestForProxy(httpRequest, apnProxyRemote), CharsetUtil.UTF_8)).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future2) throws Exception {
if (!future2.channel().config().getOption(ChannelOption.AUTO_READ)) {
future2.channel().read();
}
}
});
} else {
HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established"));
uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future2) throws Exception {
// remove handlers
uaChannelCtx.pipeline().remove("codec");
uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);
// add relay handler
uaChannelCtx.pipeline().addLast(new ApnProxyRelayHandler("UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel()));
}
});
}
} else {
if (uaChannelCtx.channel().isActive()) {
uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
}
});
}
ReferenceCountUtil.release(msg);
}
use of io.netty.bootstrap.Bootstrap in project apn-proxy by apn-proxy.
the class TestProxyWithNetty method test.
public void test(String host, String path) {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new TestHttpClientChannelInitializer());
// Make the connection attempt.
Channel ch = b.connect("127.0.0.1", ApnProxyConfig.getConfig().getPort()).sync().channel();
// Prepare the HTTP request.
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://" + host + path);
request.headers().set(HttpHeaders.Names.HOST, host);
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
//request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
// Send the HTTP request.
ch.writeAndFlush(request);
// Wait for the server to close the connection.
ch.closeFuture().sync();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
}
}
Aggregations