Example usage for io.netty.channel ChannelFuture isSuccess

List of usage examples for io.netty.channel ChannelFuture isSuccess

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:me.jtalk.socketconnector.io.TCPManager.java

License:Open Source License

public long connect(InetSocketAddress target) throws ResourceException {
    try {//  www. j  a v  a2s .co  m
        log.finest(String.format("Connection initialization to %s: starting", target));

        ChannelFuture completed = this.client.connect(target).sync();
        if (!completed.isSuccess()) {
            throw new EISSystemException("Connection failed", completed.cause());
        }
        Receiver handler = completed.channel().pipeline().get(Receiver.class);
        long connId = handler.getId();

        return connId;

    } catch (InterruptedException e) {
        throw new EISSystemException("Execution interrupted during connecting to remote client", e);
    }
}

From source file:me.jtalk.socketconnector.io.TCPManager.java

License:Open Source License

public long listen(InetSocketAddress local) throws ResourceException {
    try {/*from ww w.ja v a  2 s .  co m*/
        log.finest(String.format("Listening to %s: starting", local));

        ChannelFuture completed = this.server.bind(local).sync();
        if (!completed.isSuccess()) {
            throw new EISSystemException("Listening failed", completed.cause());
        }
        long connId = this.ids.incrementAndGet();

        log.finest(String.format("Listening to %s: connection id %d", local, connId));
        this.register(connId, completed.channel(), true);

        return connId;

    } catch (InterruptedException e) {
        throw new EISSystemException("Execution interrupted during listening setup", e);
    }
}

From source file:me.melchor9000.net.Socket.java

License:Open Source License

/**
 * Binds the socket to a random port and connects to the remote endpoint
 * asynchronously. Returns a {@link Future} where the task can be managed.
 * @param endpoint remote endpoint to connect
 * @return {@link Future} of the task/*  ww w .j  a va  2 s.  c  o m*/
 */
public @NotNull Future<Void> connectAsync(@NotNull SocketAddress endpoint) {
    return createFuture(bootstrap.connect(endpoint).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            channel = future.channel();
            if (future.isSuccess()) {
                bootstrap = null;
            }
        }
    }));
}

From source file:mmo.server.Server.java

License:Open Source License

public void run(String host, int port) {
    parentGroup = new NioEventLoopGroup();
    childGroup = new NioEventLoopGroup();

    new ServerBootstrap().group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new HttpServerCodec(), //
                            new HttpObjectAggregator(65536), //
                            routeHandlerProvider.get());

                }/*  w w  w  .j a  v a  2s  .  c o  m*/
            }).option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(16384)).bind(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        L.error("Error setting up server channel: {}", future.cause(), null);
                        new Thread(() -> { // TODO shutdown program
                            // gracefuller
                            try {
                                shutdown();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } finally {
                                System.exit(1);
                            }
                        }).start();
                    }
                }
            });
}

From source file:nats.client.NatsImpl.java

License:Open Source License

private void connect() {
    synchronized (lock) {
        if (closed) {
            return;
        }//w  ww.j  a  va  2s. c  om
    }
    final ServerList.Server server = serverList.nextServer();
    LOGGER.debug("Attempting to connect to {} with user {}", server.getAddress(), server.getUser());
    new Bootstrap().group(eventLoopGroup).remoteAddress(server.getAddress()).channel(NioSocketChannel.class)
            .handler(new NatsChannelInitializer()).connect().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        LOGGER.info("Connection to {} successful", server.getAddress());
                        server.connectionSuccess();
                        synchronized (lock) {
                            channel = future.channel();
                            if (closed) {
                                channel.close();
                            }
                        }
                    } else {
                        LOGGER.warn("Connection to {} failed", server.getAddress());
                        server.connectionFailure();
                        scheduleReconnect();
                    }
                }
            });
}

From source file:net.hasor.rsf.remoting.transport.customer.InnerClientManager.java

License:Apache License

private synchronized AbstractRsfClient connSocket(final Address hostAddress) {
    final URL hostURL = hostAddress.getAddress();
    Bootstrap boot = new Bootstrap();
    boot.group(this.rsfContext.getLoopGroup());
    boot.channel(NioSocketChannel.class);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            Channel channel = ch.pipeline().channel();
            NetworkConnection.initConnection(hostURL, channel);
            LoggerHelper.logInfo("initConnection connect %s.", hostURL);
            ///*from   w ww. j av a 2  s  .co  m*/
            ch.pipeline().addLast(new RSFCodec(), new InnerRsfCustomerHandler(getRequestManager()));
        }
    });
    ChannelFuture future = null;
    SocketAddress remote = new InetSocketAddress(hostURL.getHost(), hostURL.getPort());
    LoggerHelper.logInfo("connect to %s ...", hostURL);
    future = boot.connect(remote);
    try {
        future.await();
    } catch (InterruptedException e) {
        LoggerHelper.logSevere("connect to %s failure , %s", hostURL, e.getMessage());
        return null;
    }
    if (future.isSuccess() == true) {
        LoggerHelper.logInfo("remote %s connected.", hostURL);
        NetworkConnection conn = NetworkConnection.getConnection(future.channel());
        return new InnerRsfClient(this.getRequestManager(), conn);
    }
    //
    try {
        LoggerHelper.logSevere("connect to %s failure , %s", hostURL, future.cause().getMessage());
        future.channel().close().await();
    } catch (InterruptedException e) {
        LoggerHelper.logSevere("close connect(%s) failure , %s", hostURL, e.getMessage());
    }
    return null;
}

From source file:net.hasor.rsf.remoting.transport.customer.RsfRequestManager.java

License:Apache License

/**???*/
private void sendRequest(RsfFuture rsfFuture) {
    //???/*  w ww  . ja va  2s  . c om*/
    RsfSettings rsfSettings = this.getRsfContext().getSettings();
    if (this.requestCount.get() >= rsfSettings.getMaximumRequest()) {
        SendLimitPolicy sendPolicy = rsfSettings.getSendLimitPolicy();
        String errorMessage = "maximum number of requests, apply SendPolicy = " + sendPolicy.name();
        LoggerHelper.logWarn(errorMessage);
        if (sendPolicy == SendLimitPolicy.Reject) {
            throw new RsfException(ProtocolStatus.ClientError, errorMessage);
        } else {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
    //RsfFilter
    final RsfRequestImpl request = (RsfRequestImpl) rsfFuture.getRequest();
    final RequestMsg rsfMessage = request.getMsg();
    //??
    final AbstractRsfClient rsfClient = this.getClientManager().getClient(request.getBindInfo());
    final long beginTime = System.currentTimeMillis();
    final long timeout = rsfMessage.getClientTimeout();
    //
    if (rsfClient == null) {
        rsfFuture.failed(new IllegalStateException("The lack of effective service provider."));
        return;
    }
    if (rsfClient.isActive() == false) {
        rsfFuture.failed(new IllegalStateException("client is closed."));
        return;
    }
    this.startRequest(
            rsfFuture);/* timeout ???request*/
    //
    ChannelFuture future = rsfClient.getChannel().writeAndFlush(rsfMessage);
    /*sendData???*/
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                return;
            }
            String errorMsg = null;
            //
            if (System.currentTimeMillis() - beginTime >= timeout) {
                errorMsg = "send request too long time(" + (System.currentTimeMillis() - beginTime)
                        + "),requestID:" + rsfMessage.getRequestID();
            }
            //?
            if (future.isCancelled()) {
                errorMsg = "send request to cancelled by user,requestID:" + rsfMessage.getRequestID();
            }
            //
            if (!future.isSuccess()) {
                if (rsfClient.isActive()) {
                    // maybe some exception, so close the channel
                    getClientManager().unRegistered(rsfClient.getHostAddress());
                }
                errorMsg = "send request error " + future.cause();
            }
            LoggerHelper.logSevere(RsfRequestManager.this + ":" + errorMsg);
            //Response
            putResponse(request.getRequestID(), new RsfException(ProtocolStatus.ClientError, errorMsg));
        }
    });
}

From source file:net.hasor.rsf.rpc.net.Connector.java

License:Apache License

/**  */
public void connectionTo(final InterAddress hostAddress, final BasicFuture<RsfChannel> result) {
    ////from w w  w .  java  2 s  .  co m
    //
    Bootstrap boot = new Bootstrap();
    boot.group(this.workLoopGroup);
    boot.channel(NioSocketChannel.class);
    boot.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelHandler[] handlerArrays = channelHandler();
            ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
            handlers.addAll(Arrays.asList(handlerArrays)); // ??
            handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF
            //
            ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()]));
        }
    });
    ChannelFuture future = configBoot(boot).connect(hostAddress.toSocketAddress());
    //
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                future.channel().close();
                logger.error("connect to {} error.", hostAddress, future.cause());
                result.failed(future.cause());
            } else {
                Channel channel = future.channel();
                logger.info("connect to {} Success.", hostAddress);
                result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Out));
            }
        }
    });
}

From source file:net.hasor.rsf.rpc.net.Connector.java

License:Apache License

/**
 * ??//w  w  w .  ja  v  a2 s.  com
 * @param listenLoopGroup ?
 */
public void startListener(NioEventLoopGroup listenLoopGroup) {
    //
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(listenLoopGroup, this.workLoopGroup);
    boot.channel(NioServerSocketChannel.class);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelHandler[] handlerArrays = channelHandler();
            ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
            handlers.addAll(Arrays.asList(handlerArrays)); // ??
            handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF
            //
            ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()]));
        }
    });
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    ChannelFuture future = configBoot(boot).bind(this.bindAddress.toSocketAddress());
    //
    final BasicFuture<RsfChannel> result = new BasicFuture<RsfChannel>();
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                future.channel().close();
                result.failed(future.cause());
            } else {
                Channel channel = future.channel();
                result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Listener));
            }
        }
    });
    try {
        this.localListener = result.get();
        logger.info("rsf Server started at {}", this.bindAddress);
    } catch (Exception e) {
        logger.error("rsf start listener error: " + e.getMessage(), e);
        throw new RsfException(ProtocolStatus.NetworkError,
                this.bindAddress.toString() + " -> " + e.getMessage());
    }
    //
}

From source file:net.hasor.rsf.rpc.net.RsfChannel.java

License:Apache License

/**? Netty*/
private void sendData(final long requestID, Object sendData, final SendCallBack callBack) {
    if (!this.channel.isActive()) {
        RsfException e = new RsfException(ProtocolStatus.NetworkError,
                "send (" + requestID + ") an error, socket Channel is close.");
        if (callBack != null) {
            callBack.failed(requestID, e);
        }// w ww  .  j a  v  a  2  s.  c  om
        return;
    }
    /*???*/
    this.sendPackets++;
    ChannelFuture future = this.channel.writeAndFlush(sendData);
    /*sendData???*/
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                if (callBack != null) {
                    callBack.complete(requestID);
                }
                return;
            }
            lastSendTime = System.currentTimeMillis();
            RsfException e = null;
            if (future.isCancelled()) {
                //?
                String errorMsg = "send request(" + requestID + ") to cancelled by user.";
                e = new RsfException(ProtocolStatus.NetworkError, errorMsg);
                logger.error(e.getMessage(), e);
                //Response
                if (callBack != null) {
                    callBack.failed(requestID, e);
                }
            } else if (!future.isSuccess()) {
                //
                Throwable ex = future.cause();
                String errorMsg = "send request(" + requestID + ") an error ->" + ex.getMessage();
                e = new RsfException(ProtocolStatus.NetworkError, errorMsg, ex);
                logger.error(e.getMessage(), e);
                //Response
                if (callBack != null) {
                    callBack.failed(requestID, e);
                }
            }
        }
    });
}