Example usage for io.netty.channel ChannelFuture channel

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

Introduction

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

Prototype

Channel channel();

Source Link

Document

Returns a channel where the I/O operation associated with this future takes place.

Usage

From source file:com.mastfrog.scamper.SctpServer.java

License:Open Source License

public ChannelFuture stop() {
    ChannelFuture theFuture;
    synchronized (this) {
        theFuture = future;//ww w. j a  v  a 2s.com
    }
    if (theFuture != null) {
        theFuture.channel().close();
    }
    return theFuture;
}

From source file:com.mastfrog.scamper.Sender.java

License:Open Source License

/**
 * Send a message using the passed channel.
 *
 * @param address The address/*from w  ww  .j  ava  2 s  . c om*/
 * @param message A future which will be notified when the message is
 * flushed to the socket
 * @param sctpChannel The ordinal of the sctp channel
 * @param l A ChannelFutureListener to be notified when the mesage is
 * flushed (remember to check <code>ChannelFuture.getCause()</code> to check
 * for failure)
 * @return a future that will be notified when the message write is
 * completed
 */
public ChannelFuture send(final Address address, final Message<?> message, final int sctpChannel,
        final ChannelFutureListener l) {
    Checks.notNull("address", address);
    Checks.notNull("message", message);
    Checks.nonNegative("sctpChannel", sctpChannel);
    logger.log(Level.FINE, "Send message to {0} on {1} type {1}",
            new Object[] { address, sctpChannel, message.type });
    return associations.connect(address).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() == null) {
                logger.log(Level.FINE, "Got back connection {0} for {1}",
                        new Object[] { future.channel().remoteAddress(), address });
            }
            ChannelFuture fut = send(future.channel(), message, sctpChannel);
            if (l != null) {
                fut.addListener(l);
            }
        }
    });
}

From source file:com.mc.netty.server.NettyServer.java

License:Open Source License

public ChannelFuture start() throws InterruptedException {
    // ??ip//w w w.  j  av  a  2s  .  c  om
    ChannelFuture future = getDefaultServerBootstrap().childHandler(new TcpChannelInitializer()).bind(port)
            .sync();
    // ServerManager.pubServer(serverUrl);
    System.out.println("steelIm???,??" + port + '.');
    channle = future.channel();
    return future;
}

From source file:com.mikesilversides.mod1.ServerTest.EchoClient.java

License:Apache License

public static void init() throws Exception { // convert main to init
    // Configure SSL.git
    //        final SslContext sslCtx;
    if (SSL) {/*from w w w. j  av a  2 s  .co  m*/
        //            sslCtx = SslContextBuilder.forClient()
        //                .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        //            sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //                     if (sslCtx != null) {
                        //                         p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        //                     }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync(); //Mike: I think this is a blocking wait
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.mikesilversides.mod1.ServerTest.StubClient.java

License:Apache License

public void run() {
    System.out.println("StubClient.run() called!");
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from   w  w  w.j  av a 2  s . c  o  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new StubClientHandler(stubPlayer));
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        // We've been interrupted: no more messages.
        System.out.println("InterruptedException caught, do return");
        return;
    } finally {
        // Shut down the event loop to terminate all threads.
        System.out.println("doing group.shutdownGracefully()");
        group.shutdownGracefully();
    }
}

From source file:com.mnxfst.stream.server.StreamAnalyzerServer.java

License:Apache License

public void run(final String configurationFilename, final int port) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    StreamAnalyzerConfiguration streamAnalyzerConfiguration = mapper.readValue(new File(configurationFilename),
            StreamAnalyzerConfiguration.class);

    // set up  the actor runtime environment
    this.rootActorSystem = ActorSystem.create("streamanalyzer");

    this.componentRegistryRef = componentRegistryInitialization();
    pipelineInitialization(streamAnalyzerConfiguration.getPipelines());
    dispatcherInitialization(streamAnalyzerConfiguration.getDispatchers(), componentRegistryRef);
    listenerInitialization(streamAnalyzerConfiguration.getListeners(), componentRegistryRef);

    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//w  w w  .  j  a v a  2  s. co  m
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StreamAnalyzerStatsHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync(); // (7)

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.mobius.software.mqtt.performance.controller.net.AbstractClient.java

License:Open Source License

public SocketAddress finishConnection(ChannelFuture future, ConnectionListener listener) {
    if (future != null) {
        Channel channel = future.channel();
        SocketAddress localAddress = channel.localAddress();
        clientListeners.put(localAddress, listener);
        clientChannels.put(localAddress, channel);
        return localAddress;
    }/*from w  w  w.  j av  a 2 s  .c o m*/

    return null;
}

From source file:com.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void openAsync(final AsyncCompletionHandler<Void> handler) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);/*from  w  w w  .j  av a  2  s . c  om*/
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS));
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive());

    if (settings.getReceiveBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize());
    }
    if (settings.getSendBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize());
    }
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(final SocketChannel ch) throws Exception {
            if (sslSettings.isEnabled()) {
                SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(),
                        address.getPort());
                engine.setUseClientMode(true);
                if (!sslSettings.isInvalidHostNameAllowed()) {
                    engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters()));
                }
                ch.pipeline().addFirst("ssl", new SslHandler(engine, false));
            }
            ch.pipeline().addLast("readTimeoutHandler",
                    new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS));
            ch.pipeline().addLast(new InboundBufferHandler());
        }
    });
    final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort());
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = channelFuture.channel();
                handler.completed(null);
            } else {
                handler.failed(future.cause());
            }
        }
    });
}

From source file:com.moshi.receptionist.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public void processRequestCommand(final ChannelHandlerContext ctx, final RemotingCommand cmd) {
    final Pair<NettyRequestProcessor, ExecutorService> matched = this.processorTable.get(cmd.getCode());
    final Pair<NettyRequestProcessor, ExecutorService> pair = null == matched ? this.defaultRequestProcessor
            : matched;//from   www . ja  v  a 2  s  . c  o  m

    if (pair != null) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    RPCHook rpcHook = NettyRemotingAbstract.this.getRPCHook();
                    if (rpcHook != null) {
                        rpcHook.doBeforeRequest(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd);
                    }

                    final RemotingCommand response = pair.getObject1().processRequest(ctx, cmd);
                    if (rpcHook != null) {
                        rpcHook.doAfterResponse(cmd, response);
                    }

                    // Oneway?
                    if (!cmd.isOnewayRPC()) {
                        if (response != null) {
                            response.setOpaque(cmd.getOpaque());
                            response.markResponseType();
                            try {
                                ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
                                    @Override
                                    public void operationComplete(ChannelFuture future) throws Exception {
                                        if (!future.isSuccess()) {
                                            plog.error("response to "
                                                    + RemotingHelper.parseChannelRemoteAddr(future.channel())
                                                    + " failed", future.cause());
                                            plog.error(cmd.toString());
                                            plog.error(response.toString());
                                        }
                                    }
                                });
                            } catch (Throwable e) {
                                plog.error("process request over, but response failed", e);
                                plog.error(cmd.toString());
                                plog.error(response.toString());
                            }
                        } else {
                            // ?processRequest?
                        }
                    }
                } catch (Throwable e) {
                    plog.error("process request exception", e);
                    plog.error(cmd.toString());

                    if (!cmd.isOnewayRPC()) {
                        final RemotingCommand response = RemotingCommand.createResponseCommand(
                                RemotingSysResponseCode.SYSTEM_ERROR, //
                                RemotingHelper.exceptionSimpleDesc(e));
                        response.setOpaque(cmd.getOpaque());
                        ctx.writeAndFlush(response);
                    }
                }
            }
        };

        try {
            // ??????
            pair.getObject2().submit(run);
        } catch (RejectedExecutionException e) {
            plog.warn(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) //
                    + ", too many requests and system thread pool busy, RejectedExecutionException " //
                    + pair.getObject2().toString() //
                    + " request code: " + cmd.getCode());
            if (!cmd.isOnewayRPC()) {
                final RemotingCommand response = RemotingCommand.createResponseCommand(
                        RemotingSysResponseCode.SYSTEM_BUSY,
                        "too many requests and system thread pool busy, please try another server");
                response.setOpaque(cmd.getOpaque());
                ctx.writeAndFlush(response);
            }
        }
    } else {
        String error = " request type " + cmd.getCode() + " not supported";
        final RemotingCommand response = RemotingCommand
                .createResponseCommand(RemotingSysResponseCode.REQUEST_CODE_NOT_SUPPORTED, error);
        response.setOpaque(cmd.getOpaque());
        ctx.writeAndFlush(response);
        plog.error(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) + error);
    }
}

From source file:com.moshi.receptionist.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*from ww w.  j av  a 2 s .c  o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroup, new NioEventLoopGroup())
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .childOption(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize)
                    //
                    .childOption(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize)

                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (NettySystemConfig.NettyPooledByteBufAllocatorEnable) {
        // ????
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
        ;
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}