use of io.netty.channel.Channel in project pravega by pravega.
the class ClientConnectionInboundHandler method channelRegistered.
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
Channel c = ctx.channel();
channel.set(c);
// release all futures waiting for channel registration to complete.
registeredFutureLatch.release(null);
log.info("Connection established {} ", ctx);
c.write(new WireCommands.Hello(WireCommands.WIRE_VERSION, WireCommands.OLDEST_COMPATIBLE_VERSION), c.voidPromise());
ScheduledFuture<?> old = keepAliveFuture.getAndSet(c.eventLoop().scheduleWithFixedDelay(new KeepAliveTask(), 20, 10, TimeUnit.SECONDS));
if (old != null) {
old.cancel(false);
}
}
use of io.netty.channel.Channel in project pravega by pravega.
the class ConnectionFactoryImpl method establishConnection.
@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
Preconditions.checkNotNull(location);
Exceptions.checkNotClosed(closed.get(), this);
final SslContext sslCtx;
if (clientConfig.isEnableTls()) {
try {
SslContextBuilder sslCtxFactory = SslContextBuilder.forClient();
if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
sslCtxFactory = sslCtxFactory.trustManager(FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
} else {
sslCtxFactory = SslContextBuilder.forClient().trustManager(new File(clientConfig.getTrustStore()));
}
sslCtx = sslCtxFactory.build();
} catch (SSLException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
} else {
sslCtx = null;
}
AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp, batchSizeTracker);
Bootstrap b = new Bootstrap();
b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
if (clientConfig.isValidateHostName()) {
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
p.addLast(sslHandler);
}
// p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new ExceptionLoggingHandler(location.getEndpoint()), new CommandEncoder(batchSizeTracker), new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), handler);
}
});
// Start the client.
CompletableFuture<ClientConnection> connectionComplete = new CompletableFuture<>();
try {
b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
// since ChannelFuture is complete future.channel() is not a blocking call.
Channel ch = future.channel();
log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress());
// Once a channel is closed the channel group implementation removes it.
allChannels.add(ch);
connectionComplete.complete(handler);
} else {
connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause()));
}
}
});
} catch (Exception e) {
connectionComplete.completeExceptionally(new ConnectionFailedException(e));
}
// check if channel is registered.
CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>();
handler.completeWhenRegistered(channelRegisteredFuture);
return connectionComplete.thenCombine(channelRegisteredFuture, (clientConnection, v) -> clientConnection);
}
use of io.netty.channel.Channel in project baseio by generallycloud.
the class NettyClientThread method main.
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", new HelloClient());
}
});
System.out.println("################## Test start ####################");
ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
System.out.println(f.isSuccess());
Channel channel = f.channel();
System.out.println("channel is active :" + channel.isActive() + ",channel:" + channel);
int len = 1024 * 64;
StringBuilder s = new StringBuilder(len);
for (int i = 0; i < len; i++) {
s.append(len % 10);
}
final String msg = s.toString();
ThreadUtil.execute(new Runnable() {
@Override
public void run() {
int i = 0;
for (; ; ) {
// String s = "hello Service! ---> :" + i;
ChannelFuture f = channel.writeAndFlush(msg);
ThreadUtil.sleep(1);
System.out.println(f.isDone() + "--------" + i);
i++;
}
}
});
ThreadUtil.sleep(Integer.MAX_VALUE);
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
use of io.netty.channel.Channel in project reactor-netty by reactor.
the class ReactorNetty method addHandlerBeforeReactorEndHandlers.
/**
* A common implementation for the {@link NettyContext#addHandlerLast(String, ChannelHandler)}
* method that can be reused by other implementors.
* <p>
* This implementation will look for reactor added handlers on the right hand side of
* the pipeline, provided they are identified with the {@link NettyPipeline#RIGHT}
* prefix, and add the handler just before the first of these.
*
* @param context the {@link NettyContext} on which to add the decoder.
* @param name the name of the decoder.
* @param handler the decoder to add before the final reactor-specific handlers.
* @see NettyContext#addHandlerLast(String, ChannelHandler).
*/
static void addHandlerBeforeReactorEndHandlers(NettyContext context, String name, ChannelHandler handler) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(handler, "handler");
Channel channel = context.channel();
boolean exists = channel.pipeline().get(name) != null;
if (exists) {
if (log.isDebugEnabled()) {
log.debug("Handler [{}] already exists in the pipeline, decoder has been skipped", name);
}
return;
}
// we need to find the correct position
String before = null;
for (String s : channel.pipeline().names()) {
if (s.startsWith(NettyPipeline.RIGHT)) {
before = s;
break;
}
}
if (before == null) {
channel.pipeline().addLast(name, handler);
} else {
channel.pipeline().addBefore(NettyPipeline.ReactiveBridge, name, handler);
}
registerForClose(shouldCleanupOnClose(channel), name, context);
if (log.isDebugEnabled()) {
log.debug("Added decoder [{}] at the end of the user pipeline, full pipeline: {}", name, channel.pipeline().names());
}
}
use of io.netty.channel.Channel in project atomix by atomix.
the class NettyMessagingService method openChannel.
private CompletableFuture<Channel> openChannel(Endpoint ep) {
Bootstrap bootstrap = bootstrapClient(ep);
CompletableFuture<Channel> retFuture = new CompletableFuture<>();
ChannelFuture f = bootstrap.connect();
f.addListener(future -> {
if (future.isSuccess()) {
retFuture.complete(f.channel());
} else {
retFuture.completeExceptionally(future.cause());
}
});
log.debug("Established a new connection to {}", ep);
return retFuture;
}
Aggregations