private void initSession(SessionProtocol desiredProtocol, ChannelFuture connectFuture, Promise<Channel> sessionPromise) { assert connectFuture.isSuccess(); final Channel ch = connectFuture.channel(); final EventLoop eventLoop = ch.eventLoop(); assert eventLoop.inEventLoop(); final ScheduledFuture<?> timeoutFuture = eventLoop.schedule(() -> { if (sessionPromise.tryFailure(new SessionProtocolNegotiationException( desiredProtocol, "connection established, but session creation timed out: " + ch))) { ch.close(); } }, connectTimeoutMillis, TimeUnit.MILLISECONDS); ch.pipeline().addLast(new HttpSessionHandler(this, ch, sessionPromise, timeoutFuture)); }
@Override public void initChannel(final Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); ChannelHandler handler = config.handler(); if (handler != null) { pipeline.addLast(handler); } ch.eventLoop().execute(new Runnable() { @Override public void run() { pipeline.addLast(new ServerBootstrapAcceptor( ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)); } }); } });
@Override public ChannelFuture shutdownOutput(final ChannelPromise promise) { EventLoop loop = eventLoop(); if (loop.inEventLoop()) { shutdownOutput0(promise); } else { loop.execute(new Runnable() { @Override public void run() { shutdownOutput0(promise); } }); } return promise; }
InternalTimerHandler(long timerID, Handler<Long> runnable, boolean periodic, long delay, ContextImpl context) { this.context = context; this.timerID = timerID; this.handler = runnable; this.periodic = periodic; this.cancelled = new AtomicBoolean(); EventLoop el = context.nettyEventLoop(); Runnable toRun = () -> context.runOnContext(this); if (periodic) { future = el.scheduleAtFixedRate(toRun, delay, delay, TimeUnit.MILLISECONDS); } else { future = el.schedule(toRun, delay, TimeUnit.MILLISECONDS); } }
nameServerComparator = new NameServerComparator(preferredAddressType.addressType()); Bootstrap b = new Bootstrap(); b.group(executor()); b.channelFactory(channelFactory); b.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true); final DnsResponseHandler responseHandler = new DnsResponseHandler(executor().<Channel>newPromise()); b.handler(new ChannelInitializer<DatagramChannel>() { @Override ChannelFuture future = b.register(); Throwable cause = future.cause(); if (cause != null) { if (cause instanceof RuntimeException) { ch = future.channel(); ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(maxPayloadSize)); ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) {
int connectTimeoutMs = (int) rpcConf.getConnectTimeoutMs(); final ChannelFuture cf = new Bootstrap() .group(eloop) .handler(new ChannelInboundHandlerAdapter() { }) .channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .connect(host, port); final Promise<Rpc> promise = eloop.next().newPromise(); final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>(); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture cf) throws Exception { promise.addListener(new GenericFutureListener<Promise<Rpc>>() { @Override public void operationComplete(Promise<Rpc> p) {
nameServerComparator = new NameServerComparator(preferredAddressType.addressType()); Bootstrap b = new Bootstrap(); b.group(executor()); b.channelFactory(channelFactory); b.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true); final DnsResponseHandler responseHandler = new DnsResponseHandler(executor().<Channel>newPromise()); b.handler(new ChannelInitializer<DatagramChannel>() { @Override ch = (DatagramChannel) b.register().channel(); ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(maxPayloadSize)); ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) {
handlerContext.channel() .eventLoop() .register(fileChannel) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { fileChannel.pipeline().fireUserEventTriggered(raf); } else { result.tryFail(future.cause());
@Override public void doConnect() { if (channel != null && channel.isActive()) { return; } final TxManagerServer txManagerServer = TxManagerLocator.getInstance().locator(); if (Objects.nonNull(txManagerServer) && StringUtils.isNoneBlank(txManagerServer.getHost()) && Objects.nonNull(txManagerServer.getPort())) { host = txManagerServer.getHost(); port = txManagerServer.getPort(); } ChannelFuture future = bootstrap.connect(host, port); LogUtil.info(LOGGER, ".....connect txManager-socket -> host:port:{}", () -> host + ":" + port); future.addListener((ChannelFutureListener) futureListener -> { if (futureListener.isSuccess()) { channel = futureListener.channel(); LogUtil.info(LOGGER, "Connect to server successfully!-> host:port:{}", () -> host + ":" + port); } else { LogUtil.info(LOGGER, "Failed to connect to server, try connect after 5s-> host:port:{}", () -> host + ":" + port); futureListener.channel().eventLoop().schedule(this::doConnect, 5, TimeUnit.SECONDS); } }); }
@Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { connectionEstablished = false; future.channel().close(); future.channel().eventLoop().schedule(() -> { bootstrap.connect().addListener(this); }, new Random().nextInt(5), TimeUnit.MINUTES); } else { channel = future.channel(); connectionEstablished = true; addCLoseDetectListener(channel); LOGGER.debug("Connection established"); } }
private void onHttp2UpgradeStreamInitialized(ChannelHandlerContext ctx, Http2MultiplexCodecStream stream) { assert stream.state() == Http2Stream.State.HALF_CLOSED_LOCAL; DefaultHttp2StreamChannel ch = new DefaultHttp2StreamChannel(stream, true); ch.outboundClosed = true; // Add our upgrade handler to the channel and then register the channel. // The register call fires the channelActive, etc. ch.pipeline().addLast(upgradeStreamHandler); ChannelFuture future = ctx.channel().eventLoop().register(ch); if (future.isDone()) { registerDone(future); } else { future.addListener(CHILD_CHANNEL_REGISTRATION_LISTENER); } }
private void doCloseSync() { final CountDownLatch outerLatch = eventLoop.submit(() -> { if (allChannels.isEmpty()) { return null; final ChannelFuture f = ch.closeFuture(); closeFutures.add(f); f.addListener((ChannelFutureListener) future -> latch.countDown()); closeFutures.forEach(f -> f.channel().close()); return latch; }).syncUninterruptibly().getNow();
private Future<Void> bind(EventLoop executor, int port) { Promise<Void> futureBind = executor.newPromise(); log.info("Starting service listener on port {}", port); ChannelFuture channelFuture = bootstrap.bind(port); channelFuture.addListener((ChannelFuture future) -> { if (future.isSuccess()) { log.info("Listening on {}", future.channel().localAddress()); this.serverChannels.add(channelFuture.channel()); futureBind.setSuccess(null); } else { log.warn("Error listening on port {}: {}", port, future.cause().getMessage()); futureBind.setFailure(future.cause()); } }); return futureBind; }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { final ChannelConfig config = ctx.channel().config(); if (config.isAutoRead()) { // stop accept new connections for 1 second to allow the channel to recover // See https://github.com/netty/netty/issues/1328 config.setAutoRead(false); ctx.channel().eventLoop().schedule(enableAutoReadTask, 1, TimeUnit.SECONDS); } // still let the exceptionCaught event flow through the pipeline to give the user // a chance to do something with it ctx.fireExceptionCaught(cause); } }
public void open0(ChannelHandlerContext ctx, final Promise<Http2StreamChannel> promise) { assert ctx.executor().inEventLoop(); final Http2StreamChannel streamChannel = ((Http2MultiplexCodec) ctx.handler()).newOutboundStream(); try { init(streamChannel); } catch (Exception e) { streamChannel.unsafe().closeForcibly(); promise.setFailure(e); return; } ChannelFuture future = ctx.channel().eventLoop().register(streamChannel); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { promise.setSuccess(streamChannel); } else if (future.isCancelled()) { promise.cancel(false); } else { if (streamChannel.isRegistered()) { streamChannel.close(); } else { streamChannel.unsafe().closeForcibly(); } promise.setFailure(future.cause()); } } }); }
if (ch == null) { Bootstrap bs = bootstrap.clone(); bs.attr(POOL_KEY, this); ChannelFuture f = connectChannel(bs); if (f.isDone()) { notifyConnect(f, promise); } else { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { EventLoop loop = ch.eventLoop(); if (loop.inEventLoop()) { doHealthCheck(ch, promise); } else { loop.execute(new Runnable() { @Override public void run() { promise.tryFailure(cause);
@Override protected void complete() { channel.eventLoop().execute(() -> channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(future -> removeFromPipeline())); }
@Override public void operationComplete(ChannelFuture channelFuture) { session.initialEventLoop.register(channelFuture.channel()).addListener(completeHandler); } });