List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:com.flysoloing.learning.network.netty.redis.RedisClient.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w.ja va 2s .com*/ 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 RedisDecoder()); p.addLast(new RedisBulkStringAggregator()); p.addLast(new RedisArrayAggregator()); p.addLast(new RedisEncoder()); p.addLast(new RedisClientHandler()); } }); // Start the connection attempt. Channel ch = b.connect(HOST, PORT).sync().channel(); // Read commands from the stdin. System.out.println("Enter Redis commands (quit to end)"); ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { final String input = in.readLine(); final String line = input != null ? input.trim() : null; if (line == null || "quit".equalsIgnoreCase(line)) { // EOF or "quit" ch.close().sync(); break; } else if (line.isEmpty()) { // skip `enter` or `enter` with spaces. continue; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line); lastWriteFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { System.err.print("write failed: "); future.cause().printStackTrace(System.err); } } }); } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { group.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.udt.echo.bytes.ByteEchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the client. final ThreadFactory connectFactory = new DefaultThreadFactory("connect"); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER); try {//from w ww.j a v a2 s. c o m final Bootstrap boot = new Bootstrap(); boot.group(connectGroup).channelFactory(NioUdtProvider.BYTE_CONNECTOR) .handler(new ChannelInitializer<UdtChannel>() { @Override public void initChannel(final UdtChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoClientHandler()); } }); // Start the client. final ChannelFuture f = boot.connect(HOST, PORT).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. connectGroup.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.udt.echo.bytes.ByteEchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { final ThreadFactory acceptFactory = new DefaultThreadFactory("accept"); final ThreadFactory connectFactory = new DefaultThreadFactory("connect"); final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.BYTE_PROVIDER); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER); // Configure the server. try {/*from w w w. ja v a 2 s . c o m*/ final ServerBootstrap boot = new ServerBootstrap(); boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.BYTE_ACCEPTOR) .option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<UdtChannel>() { @Override public void initChannel(final UdtChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoServerHandler()); } }); // Start the server. final ChannelFuture future = boot.bind(PORT).sync(); // Wait until the server socket is closed. future.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. acceptGroup.shutdownGracefully(); connectGroup.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.udt.echo.message.MsgEchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the client. final ThreadFactory connectFactory = new DefaultThreadFactory("connect"); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.MESSAGE_PROVIDER); try {//w w w . j av a2 s . co m final Bootstrap boot = new Bootstrap(); boot.group(connectGroup).channelFactory(NioUdtProvider.MESSAGE_CONNECTOR) .handler(new ChannelInitializer<UdtChannel>() { @Override public void initChannel(final UdtChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoClientHandler()); } }); // Start the client. final ChannelFuture f = boot.connect(HOST, PORT).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. connectGroup.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.udt.echo.message.MsgEchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { final ThreadFactory acceptFactory = new DefaultThreadFactory("accept"); final ThreadFactory connectFactory = new DefaultThreadFactory("connect"); final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.MESSAGE_PROVIDER); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.MESSAGE_PROVIDER); // Configure the server. try {/*from w w w. j av a 2s .co m*/ final ServerBootstrap boot = new ServerBootstrap(); boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.MESSAGE_ACCEPTOR) .option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<UdtChannel>() { @Override public void initChannel(final UdtChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoServerHandler()); } }); // Start the server. final ChannelFuture future = boot.bind(PORT).sync(); // Wait until the server socket is closed. future.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. acceptGroup.shutdownGracefully(); connectGroup.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvous.MsgEchoPeerBase.java
License:Apache License
public void run() throws Exception { // Configure the peer. final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous"); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.MESSAGE_PROVIDER); try {//from w w w . j a v a2s. c o m final Bootstrap boot = new Bootstrap(); boot.group(connectGroup).channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS) .handler(new ChannelInitializer<UdtChannel>() { @Override public void initChannel(final UdtChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoPeerHandler(messageSize)); } }); // Start the peer. final ChannelFuture f = boot.connect(peer, self).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. connectGroup.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvousBytes.ByteEchoPeerBase.java
License:Apache License
public void run() throws Exception { final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous"); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER); try {/* w w w . ja v a 2s .c om*/ final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(connectGroup).channelFactory(NioUdtProvider.BYTE_RENDEZVOUS) .handler(new ChannelInitializer<UdtChannel>() { @Override protected void initChannel(UdtChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoPeerHandler(messageSize)); } }); final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync(); future.channel().closeFuture().sync(); } finally { connectGroup.shutdownGracefully(); } }
From source file:com.foilen.smalltools.net.netty.NettyClient.java
License:Open Source License
public void connect(String hostname, int port, final RSATrustedCertificates trustedCertificates, final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) { AssertTools.assertNull(channel, "Client is already connected"); try {/*from w ww . j a v a 2 s . co m*/ Bootstrap bootstrap = new Bootstrap(); bootstrap.group(NettyCommon.EVENT_LOOP_GROUP); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel socketChannel) throws Exception { // Add sslCtx if needed if (trustedCertificates != null || certificate != null) { TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null : RSATools.createTrustManagerFactory(trustedCertificates); KeyManagerFactory keyManagerFactory = certificate == null ? null : RSATools.createKeyManagerFactory(certificate); CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE; SslContext sslCtx = SslContext.newClientContext(SslProvider.JDK, null, trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter, null, 0, 0); socketChannel.pipeline().addLast(sslCtx.newHandler(socketChannel.alloc())); } // Add the channel handlers for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) { socketChannel.pipeline() .addLast(ReflectionTools.instantiate( channelHandlerContainer.getChannelHandlerClass(), channelHandlerContainer.getConstructorParams())); } } }); logger.info("Connecting to {}:{}", hostname, port); channel = bootstrap.connect(hostname, port).sync().channel(); } catch (InterruptedException e) { logger.info("Connection to {}:{} was interrupted while being created", hostname, port); throw new SmallToolsException("Connection was interrupted"); } }
From source file:com.foilen.smalltools.net.netty.NettyServer.java
License:Open Source License
/** * Start the server./* w w w .j a v a 2 s . c om*/ * * @param port * the port to listen on (0 for a random port ; get it with {@link #getPort()}) * @param trustedCertificates * (optional) the certificate to trust connections from * @param certificate * (optional) the server's certificate * @param channelHandlerContainers * the channel handlers for the incoming connections */ public void start(final int port, final RSATrustedCertificates trustedCertificates, final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) { AssertTools.assertNull(thread, "Server is already started"); final CountDownLatch countDownLatch = new CountDownLatch(1); thread = new Thread(() -> { try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(NettyCommon.EVENT_LOOP_GROUP, NettyCommon.EVENT_LOOP_GROUP); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { InetSocketAddress remoteAddress = socketChannel.remoteAddress(); logger.info("Got a connection from {}:{}", remoteAddress.getHostName(), remoteAddress.getPort()); // Add sslCtx if needed if (trustedCertificates != null || certificate != null) { TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null : RSATools.createTrustManagerFactory(trustedCertificates); KeyManagerFactory keyManagerFactory = certificate == null ? null : RSATools.createKeyManagerFactory(certificate); CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE; SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, null, trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter, null, 0, 0); SslHandler sslHandler = sslCtx.newHandler(socketChannel.alloc()); if (trustManagerFactory == null) { logger.debug("Will not verify client's identity"); } else { logger.debug("Will verify client's identity"); SSLEngine sslEngine = sslHandler.engine(); sslEngine.setNeedClientAuth(true); } socketChannel.pipeline().addLast(sslHandler); } // Add the channel handlers for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) { socketChannel.pipeline() .addLast(ReflectionTools.instantiate( channelHandlerContainer.getChannelHandlerClass(), channelHandlerContainer.getConstructorParams())); } } }) // .option(ChannelOption.SO_BACKLOG, 128) // .childOption(ChannelOption.SO_KEEPALIVE, true); bindedPort = port; logger.info("Server on port {} is starting...", port); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); SocketAddress socketAddress = channelFuture.channel().localAddress(); if (socketAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress; bindedPort = inetSocketAddress.getPort(); } logger.info("Server on port {} is started", bindedPort); countDownLatch.countDown(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { logger.info("Server on port {} is interrupted", bindedPort); } finally { countDownLatch.countDown(); } logger.info("Server on port {} is stopped", bindedPort); }); thread.setName("Netty Server-" + bindedPort); thread.start(); try { countDownLatch.await(); } catch (InterruptedException e) { logger.error("Interrupted while waiting for the server to start"); } }
From source file:com.frank.netty.protocol.http.fileServer.HttpFileServer.java
License:Apache License
public void run(final int port, final String url) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from ww w . j a v a2 s . c om ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url)); } }); ChannelFuture future = b.bind("192.168.1.102", port).sync(); System.out.println( "HTTP??? : " + "http://192.168.1.102:" + port + url); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }