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.digitalpetri.opcua.stack.server.tcp.SocketServer.java

License:Apache License

public synchronized void bind() throws ExecutionException, InterruptedException {
    if (channel != null)
        return; // Already bound

    CompletableFuture<Void> bindFuture = new CompletableFuture<>();

    bootstrap.bind(address).addListener(new ChannelFutureListener() {
        @Override//  w  w w . jav a 2s  .  c  o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                bindFuture.complete(null);
            } else {
                bindFuture.completeExceptionally(future.cause());
            }
        }
    });

    bindFuture.get();
}

From source file:com.dingwang.netty.client.DiscardClient.java

License:Open Source License

public void run() {
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    //BootStrapServerBootstrap,???channel?channel
    Bootstrap b = new Bootstrap();

    //?EventLoopGroup?bossworkder
    //??boss/*from ww w. j  a v  a 2s  .  com*/
    b.group(workerGroup);

    //NioServerSocketChannelNioSocketChannel,channel
    b.channel(NioSocketChannel.class);

    //??ServerBootstrap?childOption()SocketChannelchannel
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TimeDecoder(), new TimeClientHandler());
        }
    });

    ChannelFuture f;
    try {
        //connect()bind()
        f = b.connect(host, port).sync();
        f.channel().writeAndFlush("dddddd");
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.dingwang.netty.client.PersonClient.java

License:Open Source License

public void run() {
    EventLoopGroup workerGroup = new NioEventLoopGroup(10);

    //BootStrapServerBootstrap,???channel?channel
    Bootstrap b = new Bootstrap();

    //?EventLoopGroup?bossworkder
    //??boss/*from   www.  java2 s  . c  o  m*/
    b.group(workerGroup);

    //NioServerSocketChannelNioSocketChannel,channel
    b.channel(NioSocketChannel.class);

    //??ServerBootstrap?childOption()SocketChannelchannel
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new PersonEncoder(), new PersonDecoder(), new PersonInHandler());
        }
    });

    ChannelFuture f;
    try {
        //connect()bind()
        f = b.connect(host, port).sync();
        ChannelPool.setChannel(f.channel());
        //            Person p = new Person();
        //            p.setAge(10);
        //            p.setName("dw");
        //            f.channel().writeAndFlush(p);

        //            Thread.currentThread().sleep(1000);
        //
        //            p.setName("test");
        //            f.channel().writeAndFlush(p);
        //            f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        //            workerGroup.shutdownGracefully();
    }
}

From source file:com.dingwang.netty.server.DiscardServer.java

License:Open Source License

public void run() {
    //NioEventLoopGroup ??I/O?Netty????EventLoopGroup
    //????????2NioEventLoopGroup
    //???boss?????worker???
    //boss?worker???
    //Channels??EventLoopGroup???
    EventLoopGroup bossGroup = new NioEventLoopGroup(5);
    EventLoopGroup workerGroup = new NioEventLoopGroup(20);

    //ServerBootstrap ?NIO????Channel??
    //????/*  www.j a va 2 s . c om*/
    ServerBootstrap b = new ServerBootstrap();

    //NioServerSocketChannel?Channel?
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            //?????ChannelChannelInitializer?
            //?Channel?DiscardServerHandle??
            //ChannelChannelPipeline???????
            //?pipline??????
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new TimeEncoder(), new DiscardServerHandler());

                }
            })
            //????TCP/IP??socket?
            //tcpNoDelaykeepAlive?ChannelOptionChannelConfig??
            //ChannelOptions
            .option(ChannelOption.SO_BACKLOG, 128)
            //option()childOption()?option()??NioServerSocketChannel??
            //childOption()???ServerChannel?NioServerSocketChannel
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    try {
        //?????8080?
        //?bind()(???)
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.dingwang.netty.server.PersonServer.java

License:Open Source License

public void run() {
    //NioEventLoopGroup ??I/O?Netty????EventLoopGroup
    //????????2NioEventLoopGroup
    //???boss?????worker???
    //boss?worker???
    //Channels??EventLoopGroup???
    EventLoopGroup bossGroup = new NioEventLoopGroup(5);
    EventLoopGroup workerGroup = new NioEventLoopGroup(20);

    //ServerBootstrap ?NIO????Channel??
    //????//from  ww w.j  a v a  2 s .co m
    ServerBootstrap b = new ServerBootstrap();

    //NioServerSocketChannel?Channel?
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            //?????ChannelChannelInitializer?
            //?Channel?DiscardServerHandle??
            //ChannelChannelPipeline???????
            //?pipline??????
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new PersonDecoder(), new PersonEncoder(), new PersonOutHandler());

                }
            })
            //????TCP/IP??socket?
            //tcpNoDelaykeepAlive?ChannelOptionChannelConfig??
            //ChannelOptions
            .option(ChannelOption.SO_BACKLOG, 128)
            //option()childOption()?option()??NioServerSocketChannel??
            //childOption()???ServerChannel?NioServerSocketChannel
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    try {
        //?????8080?
        //?bind()(???)
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.dingwang.rpc.client.RpcClient.java

License:Open Source License

public RpcResponse send(RpcRequest request) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from ww w  .j a va  2  s .c o  m*/
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast(new RpcEncoder(RpcRequest.class)) //  RPC ???
                        .addLast(new RpcDecoder(RpcResponse.class)) //  RPC ????
                        .addLast(RpcClient.this); //  RpcClient ?? RPC 
            }
        }).option(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture future = bootstrap.connect(host, port).sync();
        future.channel().writeAndFlush(request).sync();

        synchronized (obj) {
            obj.wait(); // ?
        }

        if (response != null) {
            future.channel().closeFuture().sync();
        }
        return response;
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.dingwang.rpc.server.RpcServer.java

License:Open Source License

@Override
public void afterPropertiesSet() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from ww  w  . j ava 2 s .c om
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new RpcDecoder(RpcRequest.class)) //  RPC ??
                                .addLast(new RpcEncoder(RpcResponse.class)) //  RPC ???
                                //                                    .addLast(new ProviderProxy()); // ? RPC 
                                .addLast(new RpcHandler(handlerMap));
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        String[] array = serverAddress.split(":");
        String host = array[0];
        int port = Integer.parseInt(array[1]);

        ChannelFuture future = bootstrap.bind(host, port).sync();
        LOGGER.debug("server started on port {}", port);

        if (serviceRegistry != null) {
            serviceRegistry.register(serverAddress); // ??
        }

        future.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.dinstone.netty.Client.java

License:Apache License

public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*  w w w . j a  va2  s. c  om*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast("dd", new ChannelHandlerAdapter() {

                        /**
                         * {@inheritDoc}
                         * 
                         * @see io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel.ChannelHandlerContext,
                         *      java.lang.Throwable)
                         */
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            System.out.println("error: ");
                            cause.printStackTrace();
                        }
                    });
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
            }
        }
    });
}

From source file:com.dinstone.rpc.netty.client.NettyConnector.java

License:Apache License

public Channel createSession() {
    long s = System.currentTimeMillis();
    ChannelFuture cf = boot.connect().awaitUninterruptibly();
    Channel channel = cf.channel();
    long t = System.currentTimeMillis() - s;
    LOG.info("create session on {} takes {}ms", channel.remoteAddress(), t);
    return channel;
}

From source file:com.diwayou.hybrid.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 w ww.j  av  a2  s  .co m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker)
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .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 (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        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);
}