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:chapter01.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();

    try {/*from www. j  a va 2 s.c om*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoClientHandler());
            }
        });

        ChannelFuture f = b.connect("localhost", 8888).sync();

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

From source file:chapter10.WebSocketServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/* w w  w.  j av a  2  s.c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("http-codec", new HttpServerCodec());
                        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        pipeline.addLast("handler", new WebSocketServerHandler());
                    }
                });

        Channel ch = b.bind(port).sync().channel();
        System.out.println("Web socket server started at port " + port + '.');
        System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

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

From source file:chat.viska.xmpp.NettyTcpSession.java

License:Apache License

@SchedulerSupport(SchedulerSupport.CUSTOM)
@Override//  ww w. j a v a  2s  . c  o  m
protected Completable openConnection(final Compression connectionCompression,
        final Compression tlsCompression) {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(nettyEventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel channel) throws SSLException {
            if (getConnection().getTlsMethod() == Connection.TlsMethod.DIRECT) {
                tlsHandler = TLS_CONTEXT_BUILDER.build().newHandler(channel.alloc());
                channel.pipeline().addLast(PIPE_TLS, tlsHandler);
            } else {
                channel.pipeline().addLast(PIPE_TLS, new ChannelDuplexHandler());
            }
            channel.pipeline().addLast(PIPE_COMPRESSOR, new ChannelDuplexHandler());
            channel.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_STANZA_SIZE_BYTE, false, false,
                    Unpooled.wrappedBuffer(">".getBytes(StandardCharsets.UTF_8))));
            channel.pipeline().addLast(new StreamClosingDetector());
            channel.pipeline().addLast(PIPE_DECODER_XML, new XmlDecoder());
            channel.pipeline().addLast(new SimpleChannelInboundHandler<XmlDocumentStart>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final XmlDocumentStart msg)
                        throws Exception {
                    if (!"UTF-8".equalsIgnoreCase(msg.encoding())) {
                        sendError(new StreamErrorException(StreamErrorException.Condition.UNSUPPORTED_ENCODING,
                                "Only UTF-8 is supported in XMPP stream."));
                    }
                }
            });
            channel.pipeline().addLast(new StreamOpeningDetector());
            channel.pipeline().addLast(new XmlFrameDecoder(MAX_STANZA_SIZE_BYTE));
            channel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
            channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final String msg)
                        throws Exception {
                    try {
                        feedXmlPipeline(preprocessInboundXml(msg));
                    } catch (SAXException ex) {
                        sendError(new StreamErrorException(StreamErrorException.Condition.BAD_FORMAT));
                    }
                }
            });
            channel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
            channel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
                }

                @Override
                public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
                    if (cause instanceof Exception) {
                        triggerEvent(new ExceptionCaughtEvent(NettyTcpSession.this, (Exception) cause));
                    } else {
                        throw new RuntimeException(cause);
                    }
                }
            });
        }
    });

    final ChannelFuture channelFuture = bootstrap.connect(getConnection().getDomain(),
            getConnection().getPort());
    return Completable.fromFuture(channelFuture).andThen(Completable.fromAction(() -> {
        this.nettyChannel = (SocketChannel) channelFuture.channel();
        nettyChannel.closeFuture().addListener(it -> changeStateToDisconnected());
    }));
}

From source file:client.DiscardClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from   ww  w . j a  v  a2s  .  c o m
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } 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:cloudfoundry.norouter.f5.dropsonde.LineEventToMetronServer.java

License:Open Source License

@Autowired
public LineEventToMetronServer(@Qualifier("boss") EventLoopGroup boss,
        @Qualifier("worker") EventLoopGroup worker, RouteRegistrar routeRegistrar, MetronClient metronClient,
        F5Properties properties) {
    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from   w ww .  j  a  va2 s.  com
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LineBasedFrameDecoder(64 * 1024));
                    ch.pipeline().addLast(new LineEventDecoder());
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            LOGGER.warn("An error occurred processing logging events from the LTM.", cause);
                            ctx.close();
                        }

                        @Override
                        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                            LOGGER.info("New connection from {}", ctx.channel().remoteAddress());
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof LogEvent) {
                                final LogEvent logEvent = (LogEvent) msg;
                                final RouteDetails routeDetails = routeRegistrar
                                        .getRouteByAddress(logEvent.getApplicationAddress());
                                if (routeDetails != null && routeDetails.getApplicationGuid() != null) {
                                    final String appGuid = routeDetails.getApplicationGuid().toString();
                                    final String message = logEvent.getMessage() + " app_id:" + appGuid;
                                    metronClient.createLogEmitter("RTR", logEvent.getLtmIdentifier())
                                            .emit(logEvent.getTimestamp(), appGuid, message);
                                }
                            } else {
                                super.channelRead(ctx, msg);
                            }
                        }
                    });
                }
            });
    bootstrap.bind(properties.getLoggingPort()).syncUninterruptibly();
    LOGGER.info("Listening for logging events from the LTM on port {}", properties.getLoggingPort());
}

From source file:club.lovety.xy.netty.test.UptimeClient.java

License:Apache License

static Bootstrap configureBootstrap(Bootstrap b, EventLoopGroup g) {
    b.group(g).channel(NioSocketChannel.class).remoteAddress(HOST, PORT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*ww  w  .  ja va2  s. c  om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 0, 0), handler);
                }
            });
    return b;
}

From source file:cn.david.main.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {/*from   w  ww.ja  v a2 s  .  c  om*/
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } 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();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:cn.david.main.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*w  ww  . ja  v a  2s .co 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.
        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:cn.npt.net.websocket.WebSocketClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "192.168.20.71" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;//from   www  . j a va 2  s  .  co  m
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final BaseWebSocketClientHandler handler = new EchoWebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
                        new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
            }
        });

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(
                        Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:cn.savor.small.netty.NettyClient.java

License:Open Source License

public void start() {
    try {//from   w w  w  . java  2s  .  c  o m
        bootstrap = new Bootstrap();
        bootstrap.group(workGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("client SocketChannel.....................................");
                        ch.pipeline().addLast("ping", new IdleStateHandler(60, 60, 80, TimeUnit.SECONDS));
                        //POJO? ?
                        ch.pipeline().addLast(new ObjectDecoder(1024 * 5,
                                ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
                        //????
                        ch.pipeline().addLast(new ObjectEncoder());

                        ch.pipeline().addLast(new NettyClientHandler(NettyClient.this, callback, mContext));
                    }
                });
        connect();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}