List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:com.fsocks.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); }//from ww w.ja v a2 s . co m }); } else { ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { //??successclient ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, request.dstAddrType(), request.dstAddr(), request.dstPort())); responseFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) { //clientremote???????local proxy ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); //? logger.info("? addressType : " + request.dstAddrType() + ", cmdType:" + request.type() + ", host:" + request.dstAddr() + ", port:" + request.dstPort()); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results logger.info("?? addressType : " + request.dstAddrType() + ", cmdType:" + request.type() + ", host:" + request.dstAddr() + ", port:" + request.dstPort()); } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:com.gdut.Netty_testing.time_server.server.TimeServer.java
License:Apache License
/** * /*w w w . jav a 2s.c o m*/ * @Title: main * @Description: TODO * @param @param args * @param @throws Exception * @return void * @throws */ public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { 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 LoggingHandler(LogLevel.INFO), new TimeEncoder(), new TimeServerHandler()); // new TimeEncoder(), } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); f.addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { // TODO Auto-generated method stub System.out.println("success " + future.isSuccess()); } }); // 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.gdut.Netty_testing.time_server.server.TimeServerHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("Inbound --- TimeServerHandler"); ChannelFuture f = ctx.writeAndFlush(new UnixTime()); f.addListener(ChannelFutureListener.CLOSE); }
From source file:com.github.ambry.rest.NettyClient.java
License:Open Source License
/** * Connects to the server at {@link #hostname}:{@link #port} and sets {@link #channelConnectFuture} that tracks the * success of the connect./* ww w . ja va 2s . co m*/ * @throws InterruptedException if the connect is interrupted. */ private void createChannel() throws InterruptedException { channelConnectFuture = b.connect(hostname, port); // add a listener to create a new channel if this channel disconnects. ChannelFuture channelCloseFuture = channelConnectFuture.channel().closeFuture(); channelCloseFuture.addListener(channelCloseListener); }
From source file:com.github.lburgazzoli.quickfixj.transport.netty.NettySocketInitiator.java
License:Apache License
/** * *///w ww.j a v a 2s. co m private void doConnect() { ChannelFuture future = m_boot.connect(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isDone() && future.isSuccess()) { setChannel(new NettyChannel(future.channel())); } else if (!future.isSuccess() && !future.isCancelled()) { LOGGER.warn("Error", future.cause()); doReconnect(); } } }); }
From source file:com.github.mrstampy.gameboot.netty.AbstractNettyProcessor.java
License:Open Source License
@Override public void sendMessage(ChannelHandlerContext ctx, Object msg, Response response) throws Exception { ChannelFuture f = sendMessage(ctx, msg); f.addListener(e -> log(e, response, ctx)); }
From source file:com.github.mrstampy.gameboot.otp.netty.OtpEncryptedNettyHandler.java
License:Open Source License
private void sendResponse(ChannelHandlerContext ctx, OtpMessage message, Response r) throws JsonProcessingException, GameBootException { ChannelFuture cf = ctx.writeAndFlush(converter.toJsonArray(r)); cf.addListener(f -> log(f, ctx, message.getType())); }
From source file:com.github.mrstampy.kitchensync.netty.Bootstrapper.java
License:Open Source License
/** * Returns a channel using the bootstrap for the specified port. Should none * exist then the default bootstrap is used. * * @param <CHANNEL>/*from ww w. j a v a2 s . c om*/ * the generic type * @param port * the port * @return the channel */ @SuppressWarnings("unchecked") public <CHANNEL extends DatagramChannel> CHANNEL bind(int port) { boolean contains = containsBootstrap(port); if (!contains && !hasDefaultBootstrap()) { log.error("Bootstrap for port {} not initialized", port); return null; } Bootstrap b = channelBootstraps.get(contains ? port : DEFAULT_BOOTSTRAP_KEY); ChannelFuture cf = b.bind(port); CountDownLatch latch = new CountDownLatch(1); cf.addListener(getBindListener(port, latch)); await(latch, "Channel creation timed out"); return cf.isSuccess() ? (CHANNEL) cf.channel() : null; }
From source file:com.github.mrstampy.kitchensync.netty.Bootstrapper.java
License:Open Source License
/** * Bind to the specified multicast address. * * @param <CHANNEL>// w w w . ja va 2 s .c o m * the generic type * @param multicast * the multicast * @return the channel */ @SuppressWarnings("unchecked") public <CHANNEL extends DatagramChannel> CHANNEL multicastBind(InetSocketAddress multicast) { String key = createMulticastKey(multicast); if (!containsMulticastBootstrap(key)) { log.error("Multicast bootstrap for {} not initialized", multicast); return null; } Bootstrap b = multicastBootstraps.get(key); ChannelFuture cf = b.bind(); CountDownLatch latch = new CountDownLatch(1); cf.addListener(getMulticastBindListener(multicast, latch)); await(latch, "Multicast channel creation timed out"); return cf.isSuccess() ? (CHANNEL) cf.channel() : null; }
From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyChannel.java
License:Open Source License
/** * Send impl./*w w w.ja v a 2 s.c o m*/ * * @param dp * the dp * @param address * the address * @return the channel future */ protected ChannelFuture sendImpl(DatagramPacket dp, InetSocketAddress address) { if (!isActive()) { log.error("Channel is not active, cannot send {} to {}", dp, address); return new KiSyFailedFuture(); } if (dp == null) { log.error("No message to send to {}", address); return new KiSyFailedFuture(); } ChannelFuture cf = getChannel().writeAndFlush(dp); cf.addListener(SEND_FUTURE); return cf; }