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.chen.opensourceframework.netty.copy.DiscardClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup group = new NioEventLoopGroup();
    try {//from w w w  .j  av  a  2  s.  c om
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new TimeDecoder(), new DiscardClientHandler());
            }
        });

        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.chen.opensourceframework.netty.copy.DiscardServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   www.ja va2s  .c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6);

        ChannelFuture f = b.bind(PORT).sync();

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

From source file:com.chen.opensourceframework.netty.discard.DiscardClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  ww w .j  av  a  2s. c o m
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(new DiscardClientHandler());
            }
        });

        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.chen.opensourceframework.netty.discard.DiscardServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* ww  w  . j a  va 2s. c o m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(new DiscardServerHandler());
                    }
                });

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

        // 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.chenyang.proxy.EchoClient.java

License:Apache License

public static void start(EventLoopGroup group) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//w ww  .  j  a  v  a 2 s  . co  m
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    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.
        System.out.println(" clients star ");
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.chenyang.proxy.EchoServer.java

License:Apache License

public static void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  w  w  w.  j av a 2 s  .c  o m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        System.out.println(" server start in port " + PORT);
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.cloudera.livy.client.local.rpc.RpcServer.java

License:Apache License

public RpcServer(LocalConf lconf) throws IOException, InterruptedException {
    this.config = lconf;
    this.group = new NioEventLoopGroup(this.config.getInt(RPC_MAX_THREADS),
            new ThreadFactoryBuilder().setNameFormat("RPC-Handler-%d").setDaemon(true).build());
    this.channel = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override// w  w w .j a va  2s.  co m
                public void initChannel(SocketChannel ch) throws Exception {
                    SaslServerHandler saslHandler = new SaslServerHandler(config);
                    final Rpc newRpc = Rpc.createServer(saslHandler, config, ch, group);
                    saslHandler.rpc = newRpc;

                    Runnable cancelTask = new Runnable() {
                        @Override
                        public void run() {
                            LOG.warn("Timed out waiting for hello from client.");
                            newRpc.close();
                        }
                    };
                    saslHandler.cancelTask = group.schedule(cancelTask,
                            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);
                }
            }).option(ChannelOption.SO_BACKLOG, 1).option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true).bind(0).sync().channel();
    this.port = ((InetSocketAddress) channel.localAddress()).getPort();
    this.pendingClients = Maps.newConcurrentMap();

    String address = config.get(RPC_SERVER_ADDRESS);
    if (address == null) {
        address = config.findLocalAddress();
    }
    this.address = address;
}

From source file:com.cloudera.livy.rsc.rpc.RpcServer.java

License:Apache License

public RpcServer(RSCConf lconf) throws IOException, InterruptedException {
    this.config = lconf;
    this.group = new NioEventLoopGroup(this.config.getInt(RPC_MAX_THREADS),
            Utils.newDaemonThreadFactory("RPC-Handler-%d"));
    this.channel = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from  ww w  .j  a v a 2s  . co  m
                public void initChannel(SocketChannel ch) throws Exception {
                    SaslServerHandler saslHandler = new SaslServerHandler(config);
                    final Rpc newRpc = Rpc.createServer(saslHandler, config, ch, group);
                    saslHandler.rpc = newRpc;

                    Runnable cancelTask = new Runnable() {
                        @Override
                        public void run() {
                            LOG.warn("Timed out waiting for hello from client.");
                            newRpc.close();
                        }
                    };
                    saslHandler.cancelTask = group.schedule(cancelTask,
                            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);
                }
            }).option(ChannelOption.SO_BACKLOG, 1).option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true).bind(0).sync().channel();
    this.port = ((InetSocketAddress) channel.localAddress()).getPort();
    this.pendingClients = new ConcurrentHashMap<>();

    String address = config.get(RPC_SERVER_ADDRESS);
    if (address == null) {
        address = config.findLocalAddress();
    }
    this.address = address;
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppClient.java

License:Apache License

/**
 * Creates a new default SmppClient.//from w w w  .j  a v a 2 s .com
 * @param workerGroup The max number of concurrent sessions expected
 *      to be active at any time.  This number controls the max number of worker
 *      threads that the underlying Netty library will use.  If processing
 *      occurs in a sessionHandler (a blocking op), be <b>VERY</b> careful
 *      setting this to the correct number of concurrent sessions you expect.
 * @param monitorExecutor The scheduled executor that all sessions will share
 *      to monitor themselves and expire requests.  If null monitoring will
 *      be disabled.
 */
public DefaultSmppClient(NioEventLoopGroup workerGroup, ScheduledExecutorService monitorExecutor) {
    this.channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    this.workerGroup = workerGroup;
    this.clientBootstrap = new Bootstrap();
    this.clientBootstrap.group(this.workerGroup);
    this.clientBootstrap.channel(NioSocketChannel.class);
    // we use the same default pipeline for all new channels - no need for a factory
    this.clientConnector = new SmppClientConnector(this.channels);

    this.clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(SmppChannelConstants.PIPELINE_CLIENT_CONNECTOR_NAME, clientConnector);
        }
    });

    this.monitorExecutor = monitorExecutor;
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppServer.java

License:Apache License

/**
 * Creates a new default SmppServer.//from  w  w  w  .  j a  va2  s  .co m
 * @param configuration The server configuration to create this server with
 * @param serverHandler The handler implementation for handling bind requests
 *      and creating/destroying sessions.
 * @param monitorExecutor The scheduled executor that all sessions will share
 *      to monitor themselves and expire requests. If null monitoring will
 *      be disabled.
 * @param bossGroup Specify the EventLoopGroup to accept new connections and
 *      handle accepted connections. The {@link EventLoopGroup} is used to handle
 *      all the events and IO for {@link SocketChannel}.
 * @param workerGroup The {@link EventLoopGroup} is used to handle all the events
 *      and IO for {@link Channel}.
 */
public DefaultSmppServer(final SmppServerConfiguration configuration, SmppServerHandler serverHandler,
        ScheduledExecutorService monitorExecutor, EventLoopGroup bossGroup, EventLoopGroup workerGroup) {
    this.configuration = configuration;
    // the same group we'll put every server channel
    this.channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    this.serverHandler = serverHandler;

    // tie the server bootstrap to this server socket channel factory
    this.serverBootstrap = new ServerBootstrap();

    // a factory for creating channels (connections)
    if (configuration.isNonBlockingSocketsEnabled()) {
        this.serverBootstrap.channel(NioServerSocketChannel.class);
    } else {
        this.serverBootstrap.channel(OioServerSocketChannel.class);
    }

    this.bossGroup = bossGroup;
    this.workerGroup = workerGroup;
    this.serverBootstrap.group(this.bossGroup, this.workerGroup);

    // set options for the server socket that are useful
    this.serverBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());

    // we use the same default pipeline for all new channels - no need for a factory
    this.serverConnector = new SmppServerConnector(channels, this);

    this.serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(SmppChannelConstants.PIPELINE_SERVER_CONNECTOR_NAME, serverConnector);
        }
    });

    // a shared timer used to make sure new channels are bound within X milliseconds
    this.bindTimer = new Timer(configuration.getName() + "-BindTimer0", true);
    // NOTE: this would permit us to customize the "transcoding" context for a server if needed
    this.transcoder = new DefaultPduTranscoder(new DefaultPduTranscoderContext());
    this.sessionIdSequence = new AtomicLong(0);
    this.monitorExecutor = monitorExecutor;
    this.counters = new DefaultSmppServerCounters();
    if (configuration.isJmxEnabled()) {
        registerMBean();
    }
}