List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.topsec.bdc.platform.api.test.file.FileServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from w ww . j a v a 2s. c om SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } p.addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(8192), new StringDecoder(CharsetUtil.UTF_8), new ChunkedWriteHandler(), new FileServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.turn.ttorrent.client.io.PeerClient.java
License:Apache License
@Nonnull public ChannelFuture connect(@Nonnull final PeerConnectionListener listener, @Nonnull final byte[] infoHash, @Nonnull final SocketAddress remoteAddress) { final ChannelFuture future; synchronized (lock) { // connect -> initAndRegister grabs this, so we can safely synchronize here. bootstrap.handler(new PeerClientHandshakeHandler(listener, infoHash, listener.getLocalPeerId())); future = bootstrap.connect(remoteAddress); }/*from ww w. ja v a2 s . c om*/ future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { LOG.trace("Succeeded: {}", future.get()); } catch (Exception e) { // LOG.error("Connection to " + remoteAddress + " failed.", e); listener.handlePeerConnectionFailed(remoteAddress, e); Channel channel = future.channel(); if (channel.isOpen()) channel.close(); // .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } } }); return future; }
From source file:com.turo.pushy.apns.ApnsChannelFactory.java
License:Open Source License
/** * Creates and connects a new channel. The initial connection attempt may be delayed to accommodate exponential * back-off requirements./*from w w w . j a va2 s . c om*/ * * @param channelReadyPromise the promise to be notified when a channel has been created and connected to the APNs * server * * @return a future that will be notified once a channel has been created and connected to the APNs server */ @Override public Future<Channel> create(final Promise<Channel> channelReadyPromise) { final long delay = this.currentDelaySeconds.get(); channelReadyPromise.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) { final long updatedDelay = future.isSuccess() ? 0 : Math.max(Math.min(delay * 2, MAX_CONNECT_DELAY_SECONDS), MIN_CONNECT_DELAY_SECONDS); ApnsChannelFactory.this.currentDelaySeconds.compareAndSet(delay, updatedDelay); } }); this.bootstrapTemplate.config().group().schedule(new Runnable() { @Override public void run() { final Bootstrap bootstrap = ApnsChannelFactory.this.bootstrapTemplate.clone() .channelFactory(new AugmentingReflectiveChannelFactory<>( ClientChannelClassUtil.getSocketChannelClass( ApnsChannelFactory.this.bootstrapTemplate.config().group()), CHANNEL_READY_PROMISE_ATTRIBUTE_KEY, channelReadyPromise)); final ChannelFuture connectFuture = bootstrap.connect(); connectFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) { if (!future.isSuccess()) { // This may seem spurious, but our goal here is to accurately report the cause of // connection failure; if we just wait for connection closure, we won't be able to // tell callers anything more specific about what went wrong. tryFailureAndLogRejectedCause(channelReadyPromise, future.cause()); } } }); connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) { // We always want to try to fail the "channel ready" promise if the connection closes; if it has // already succeeded, this will have no effect. channelReadyPromise.tryFailure( new IllegalStateException("Channel closed before HTTP/2 preface completed.")); } }); } }, delay, TimeUnit.SECONDS); return channelReadyPromise; }
From source file:com.turo.pushy.apns.ApnsClientHandler.java
License:Open Source License
@Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception { if (event instanceof IdleStateEvent) { log.trace("Sending ping due to inactivity."); this.encoder().writePing(context, false, System.currentTimeMillis(), context.newPromise()) .addListener(new GenericFutureListener<ChannelFuture>() { @Override/* w ww . j a va 2s.c o m*/ public void operationComplete(final ChannelFuture future) { if (!future.isSuccess()) { log.debug("Failed to write PING frame.", future.cause()); future.channel().close(); } } }); this.pingTimeoutFuture = context.channel().eventLoop().schedule(new Runnable() { @Override public void run() { log.debug("Closing channel due to ping timeout."); context.channel().close(); } }, pingTimeoutMillis, TimeUnit.MILLISECONDS); this.flush(context); } super.userEventTriggered(context, event); }
From source file:com.turo.pushy.apns.BenchmarkApnsServer.java
License:Open Source License
public Future<Void> start(final int port) { final ChannelFuture channelFuture = this.bootstrap.bind(port); this.allChannels = new DefaultChannelGroup(channelFuture.channel().eventLoop(), true); this.allChannels.add(channelFuture.channel()); return channelFuture; }
From source file:com.turo.pushy.apns.MockApnsServer.java
License:Open Source License
/** * Starts this mock server and listens for traffic on the given port. * * @param port the port to which this server should bind * * @return a {@code Future} that will succeed when the server has bound to the given port and is ready to accept * traffic/*w w w. j ava2s .c o m*/ */ public Future<Void> start(final int port) { final ChannelFuture channelFuture = this.bootstrap.bind(port); this.allChannels = new DefaultChannelGroup(channelFuture.channel().eventLoop(), true); this.allChannels.add(channelFuture.channel()); return channelFuture; }
From source file:com.turo.pushy.apns.server.BaseHttp2Server.java
License:Open Source License
/** * Starts this mock server and listens for traffic on the given port. * * @param port the port to which this server should bind * * @return a {@code Future} that will succeed when the server has bound to the given port and is ready to accept * traffic// w ww . ja va2 s. co m */ public Future<Void> start(final int port) { final ChannelFuture channelFuture = this.bootstrap.bind(port); this.allChannels.add(channelFuture.channel()); return channelFuture; }
From source file:com.twocater.diamond.core.test.DiscardServer.java
public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w w w. ja va 2 s . c om*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new DiscardServerHandler()); } }); b.option(ChannelOption.SO_BACKLOG, 128); b.childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); System.out.println("bind"); f.channel().closeFuture().sync(); System.out.println("close"); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:com.twocater.diamond.core.test.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/* ww w.ja v a 2s. c o m*/ boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); keepAlive = false; if (!keepAlive) { ctx.write(response).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { channelFuture.channel().close(); System.out.println("asdfsadasdfsdfsadfsadfsdfsdfdfasdfasdfasdfasdfasf"); } }); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:com.uber.tchannel.api.TChannel.java
License:Open Source License
public ChannelFuture listen() throws InterruptedException { ChannelFuture f = this.serverBootstrap.bind(this.host, this.port).sync(); InetSocketAddress localAddress = (InetSocketAddress) f.channel().localAddress(); this.listeningPort = localAddress.getPort(); this.listeningHost = localAddress.getAddress().getHostAddress(); this.peerManager.setHostPort(String.format("%s:%d", this.listeningHost, this.listeningPort)); return f;/* www . j av a2 s.com*/ }