Example usage for io.netty.channel ChannelFutureListener ChannelFutureListener

List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelFutureListener ChannelFutureListener.

Prototype

ChannelFutureListener

Source Link

Usage

From source file:com.newlandframework.rpc.netty.MessageRecvExecutor.java

License:Apache License

public static void submit(Callable<Boolean> task, final ChannelHandlerContext ctx, final MessageRequest request,
        final MessageResponse response) {
    if (threadPoolExecutor == null) {
        synchronized (MessageRecvExecutor.class) {
            if (threadPoolExecutor == null) {
                threadPoolExecutor = MoreExecutors
                        .listeningDecorator((ThreadPoolExecutor) (RpcSystemConfig.isMonitorServerSupport()
                                ? RpcThreadPool.getExecutorWithJmx(threadNums, queueNums)
                                : RpcThreadPool.getExecutor(threadNums, queueNums)));
            }//  w w  w  .j a  va 2  s. co m
        }
    }

    ListenableFuture<Boolean> listenableFuture = threadPoolExecutor.submit(task);
    Futures.addCallback(listenableFuture, new FutureCallback<Boolean>() {
        public void onSuccess(Boolean result) {
            ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("RPC Server Send message-id respone:" + request.getMessageId());
                }
            });
        }

        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    }, threadPoolExecutor);
}

From source file:com.newlandframework.rpc.netty.MessageSendInitializeTask.java

License:Apache License

public Boolean call() {
    Bootstrap b = new Bootstrap();
    b.group(eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new MessageSendChannelInitializer().buildRpcSerializeProtocol(protocol));

    ChannelFuture channelFuture = b.connect(serverAddress);
    channelFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(final ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                MessageSendHandler handler = channelFuture.channel().pipeline().get(MessageSendHandler.class);
                RpcServerLoader.getInstance().setMessageSendHandler(handler);
            }/*from  ww  w.ja va 2s.c  o  m*/
        }
    });
    return Boolean.TRUE;
}

From source file:com.nitesh.netty.snoop.client.HttpSnoopClient.java

License:Apache License

private void sendRequest() {
    // Prepare the HTTP request.
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            uri.getRawPath());// ww  w .j a  va  2s. com
    //HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.headers().set(HttpHeaders.Names.HOST, host);
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);

    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
            .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

    // Send the HTTP request.
    ch.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            System.out.println("Request sent. Success? " + future.isSuccess());
            if (!future.isSuccess()) {
                future.cause().printStackTrace(System.out);
            }
        }
    });
}

From source file:com.nus.mazegame.client.GameClientHandler.java

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    this.ctx = ctx;
    if (rsender == null) {
        rsender = new RetrySender(instance);
        ui.init();//from   w ww  .  j  av a 2  s . co m
    }

    ChannelFuture closeFuture = ctx.channel().closeFuture();
    closeFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            System.out.println("Master lost, connect to slave...");
            GameClient.init(GameInfo.instance.getSlaveAddr(), GameInfo.instance.getHostPort() + 1,
                    MNodeType.CLIENT, ctx.channel().localAddress());
        }

    });
}

From source file:com.nus.mazegame.server.GameServerHandler.java

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    synchronized (instance) {
        if (rsender == null) {
            // when client connect to this slave, means master failed
            if (GameService.gameService.isIsSlave()) {
                Logger.getLogger(GameServerHandler.class.getName()).log(Level.INFO, "Master lost...");
                new Thread() {
                    @Override/*from  w ww  .  j  a  v a  2s . co m*/
                    public void run() {
                        try {
                            GameService.gameService.end(GameService.gameService.getMasterId());
                            GameService.gameService.promoteSlave();
                            GameService.gameService.changeSlave();
                        } catch (Exception ex) {
                            Logger.getLogger(GameService.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }.start();

            }
            rsender = new RetrySender(instance);
        }
    }
    String clientSocketAddr = ((InetSocketAddress) ctx.channel().remoteAddress()).toString();
    Logger.getLogger(GameServerHandler.class.getName()).log(Level.INFO, "New user connected...{0}",
            clientSocketAddr);
    CNameChannelMap.putIfAbsent(clientSocketAddr, ctx);
    CName = clientSocketAddr;
    clientAddr = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostName();
    addressBook.putIfAbsent(clientSocketAddr, clientAddr);

    ChannelFuture closeFuture = ctx.channel().closeFuture();
    closeFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (userId == GameService.gameService.getMasterId()) {
                Logger.getLogger(GameServerHandler.class.getName()).log(Level.SEVERE,
                        "Master server failed but client still alive...");
            } else if (userId == GameService.gameService.getSlaveId()) {
                Logger.getLogger(GameServerHandler.class.getName()).log(Level.INFO,
                        "Slave node lost...userId:{0}", userId);
                // this case when slave dead
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            GameService.gameService.end(userId);
                            GameService.gameService.changeSlave();
                        } catch (Exception ex) {
                            Logger.getLogger(GameService.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }.start();
            } else {
                Logger.getLogger(GameServerHandler.class.getName()).log(Level.INFO,
                        "Client node lost...userId:{0}", userId);
                GameService.gameService.end(userId);

                MsgHeader header = new MsgHeader();
                header.setUserId(userId);
                GeneralResponsePacket endPacket = new GeneralResponsePacket();
                endPacket.setType(GeneralResponseType.END);
                endPacket.setStatus(ResponseStatus.SUCCESS);
                String msgId3 = RetrySender.genMsgKey(GameService.gameService.getMasterId());
                header.setMsgId(msgId3);
                header.setAction(Command.UPDATE_END);
                SendPacketTask task2 = new SendPacketTask(header.getMsgId(), header, endPacket);
                task2.setCloseCtx(false);
                rsender.send(task2);
            }
        }

    });
}

From source file:com.nus.mazegame.server.GameServerHandler.java

public void sendMsg(final ChannelHandlerContext ctx, byte[] msg, boolean closeCtx) {
    final ChannelFuture f = ctx.writeAndFlush(msg);
    if (closeCtx) {
        f.addListener(new ChannelFutureListener() {
            @Override/*from  w  ww . j  a  v  a 2s . co  m*/
            public void operationComplete(ChannelFuture future) {
                assert f == future;
                ctx.close();
            }
        });
    }
}

From source file:com.outbrain.pajamasproxy.memcached.server.MemCacheDaemon.java

License:Apache License

private void createBootstratp() {
    log.info("Initializing TCP...");
    ServerBootstrap tcpBootstrap = new ServerBootstrap();
    tcpBootstrap.group(eventLoopGroup);//from  www  . j av  a 2s.c  o  m
    tcpBootstrap.channel(NioServerSocketChannel.class);
    tcpBootstrap.childHandler(serverPipelineFactory);

    final ChannelFuture channelFuture = tcpBootstrap.bind(addr).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            log.info("Server started; listening to {}", addr);
            running = true;
        }
    });
}

From source file:com.repo.netty.factorial.FactorialClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, final BigInteger msg) {
    receivedMessages++;//  www  .  j  a  v  a  2  s.  c om
    if (receivedMessages == FactorialClient.COUNT) {
        // Offer the answer after closing the connection.
        ctx.channel().close().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                boolean offered = answer.offer(msg);
                assert offered;
            }
        });
    }
}

From source file:com.repo.netty.proxy.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();// www.j  a v  a 2 s.co m
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:com.sangupta.swift.netty.proxy.ProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext channelHandlerContext, Object message) {
    inboundChannel.writeAndFlush(message).addListener(new ChannelFutureListener() {

        @Override/*from  w  w  w . j  a  v  a2 s  . c  o  m*/
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                channelHandlerContext.channel().read();
            } else {
                future.channel().close();
            }
        }

    });
}