Example usage for io.netty.channel ChannelInitializer ChannelInitializer

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

Introduction

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

Prototype

ChannelInitializer

Source Link

Usage

From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java

License:Apache License

public CompletableFuture<ModbusTcpSlave> bind(String host, int port) {
    CompletableFuture<ModbusTcpSlave> bindFuture = new CompletableFuture<>();

    ServerBootstrap bootstrap = new ServerBootstrap();

    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
        @Override/* w ww .j  a  v  a  2  s.c  om*/
        protected void initChannel(SocketChannel channel) throws Exception {
            channelCounter.inc();
            logger.info("channel initialized: {}", channel);

            channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            channel.pipeline()
                    .addLast(new ModbusTcpCodec(new ModbusResponseEncoder(), new ModbusRequestDecoder()));
            channel.pipeline().addLast(new ModbusTcpSlaveHandler(ModbusTcpSlave.this));

            channel.closeFuture().addListener(future -> channelCounter.dec());
        }
    };

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(initializer)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    bootstrap.bind(host, port).addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            Channel channel = future.channel();
            serverChannels.put(channel.localAddress(), channel);
            bindFuture.complete(ModbusTcpSlave.this);
        } else {
            bindFuture.completeExceptionally(future.cause());
        }
    });

    return bindFuture;
}

From source file:com.digitalpetri.opcua.stack.client.UaTcpStackClient.java

License:Apache License

public static CompletableFuture<ClientSecureChannel> bootstrap(UaTcpStackClient client,
        Optional<ClientSecureChannel> existingChannel) {

    CompletableFuture<ClientSecureChannel> handshake = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(client.getConfig().getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  ww w.j  av a 2s.co m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    UaTcpClientAcknowledgeHandler acknowledgeHandler = new UaTcpClientAcknowledgeHandler(client,
                            existingChannel, handshake);

                    channel.pipeline().addLast(acknowledgeHandler);
                }
            });

    try {
        URI uri = URI.create(client.getEndpointUrl());

        bootstrap.connect(uri.getHost(), uri.getPort()).addListener((ChannelFuture f) -> {
            if (!f.isSuccess()) {
                handshake.completeExceptionally(f.cause());
            }
        });
    } catch (Throwable t) {
        UaException failure = new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid,
                "endpoint URL invalid: " + client.getEndpointUrl());

        handshake.completeExceptionally(failure);
    }

    return handshake;
}

From source file:com.digitalpetri.opcua.stack.server.tcp.SocketServer.java

License:Apache License

private SocketServer(InetSocketAddress address) {
    this.address = address;

    bootstrap.group(Stack.sharedEventLoop()).handler(new LoggingHandler(SocketServer.class))
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//w w w.  jav a  2  s.c o m
                protected void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new UaTcpServerHelloHandler(SocketServer.this));
                }
            });
}

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  w  w  w .  ja v  a  2s  .  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 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// w w  w . j  av  a 2  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??
    //????//w  w  w  . java  2  s.  com
    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   w w w.j  ava2s  .com*/
    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   w ww .  j  a v a2 s.  com
        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.jrpc.transport.netty4.NettyAcceptance.java

License:Apache License

@Override
public Acceptance bind() {
    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("N4A-Boss"));
    workGroup = new NioEventLoopGroup(transportConfig.getNioProcessorCount(),
            new DefaultThreadFactory("N4A-Work"));

    ServerBootstrap boot = new ServerBootstrap().group(bossGroup, workGroup);
    boot.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override//from  w  w  w  .j  a va  2s.c om
        public void initChannel(SocketChannel ch) throws Exception {
            TransportProtocolDecoder decoder = new TransportProtocolDecoder();
            decoder.setMaxObjectSize(transportConfig.getMaxSize());
            TransportProtocolEncoder encoder = new TransportProtocolEncoder();
            encoder.setMaxObjectSize(transportConfig.getMaxSize());
            ch.pipeline().addLast("TransportProtocolDecoder", decoder);
            ch.pipeline().addLast("TransportProtocolEncoder", encoder);

            int intervalSeconds = transportConfig.getHeartbeatIntervalSeconds();
            ch.pipeline().addLast("IdleStateHandler", new IdleStateHandler(intervalSeconds * 2, 0, 0));
            ch.pipeline().addLast("NettyServerHandler", new NettyServerHandler());
        }
    });
    boot.option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_BACKLOG, 128);
    boot.childOption(ChannelOption.SO_RCVBUF, 16 * 1024).childOption(ChannelOption.SO_SNDBUF, 16 * 1024)
            .childOption(ChannelOption.TCP_NODELAY, true);

    try {
        boot.bind(serviceAddress).sync();

        int processorCount = transportConfig.getBusinessProcessorCount();
        if (processorCount > 0) {
            NamedThreadFactory threadFactory = new NamedThreadFactory("N4A-BusinessProcessor");
            executorService = Executors.newFixedThreadPool(processorCount, threadFactory);
        }
    } catch (Exception e) {
        throw new RuntimeException("can't bind service on " + serviceAddress, e);
    }
    LOG.info("netty acceptance bind on {}", serviceAddress);

    return this;
}