List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:com.bianlz.ndg.p14.server.NettyServer.java
License:Apache License
public void bind() throws Exception { // ??NIO/*from w ww .ja va2 s.c o m*/ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); 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 IOException { ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast(new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(5000)); ch.pipeline().addLast(new LoginAuthRespHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler()); } }); // ??? b.bind(Constant.REMOTEIP, Constant.PORT).sync(); System.out.println("Netty server start ok : " + (Constant.REMOTEIP + " : " + Constant.PORT)); }
From source file:com.bloom.zerofs.rest.NettyServerFactory.java
License:Open Source License
/** * Creates a new instance of NettyServerFactory. * @param verifiableProperties the in-memory {@link VerifiableProperties} to use. * @param metricRegistry the {@link MetricRegistry} to use. * @param requestHandler the {@link RestRequestHandler} to hand off the requests to. * @param publicAccessLogger the {@link PublicAccessLogger} that can be used for public access logging * @param restServerState the {@link RestServerState} that can be used to check the health of the system * to respond to health check requests * @throws IllegalArgumentException if any of the arguments are null. *//*from w w w. j a v a 2 s. c om*/ public NettyServerFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry, final RestRequestHandler requestHandler, final PublicAccessLogger publicAccessLogger, final RestServerState restServerState) { if (verifiableProperties == null || metricRegistry == null || requestHandler == null || publicAccessLogger == null || restServerState == null) { throw new IllegalArgumentException("Null arg(s) received during instantiation of NettyServerFactory"); } else { nettyConfig = new NettyConfig(verifiableProperties); nettyMetrics = new NettyMetrics(metricRegistry); final ConnectionStatsHandler connectionStatsHandler = new ConnectionStatsHandler(nettyMetrics); channelInitializer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline() // connection stats handler to track connection related metrics .addLast("connectionStatsHandler", connectionStatsHandler) // for http encoding/decoding. Note that we get content in 8KB chunks and a change to that number has // to go here. .addLast("codec", new HttpServerCodec(nettyConfig.nettyServerMaxInitialLineLength, nettyConfig.nettyServerMaxHeaderSize, nettyConfig.nettyServerMaxChunkSize)) // for health check request handling .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics)) // for public access logging .addLast("publicAccessLogHandler", new PublicAccessLogHandler(publicAccessLogger, nettyMetrics)) // for detecting connections that have been idle too long - probably because of an error. .addLast("idleStateHandler", new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds)) // for safe writing of chunks for responses .addLast("chunker", new ChunkedWriteHandler()) // custom processing class that interfaces with a BlobStorageService. .addLast("processor", new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler)); } }; } }
From source file:com.bloom.zerofs.tools.perf.rest.NettyPerfClient.java
License:Open Source License
/** * Starts the NettyPerfClient./* w w w .j a v a2s . c om*/ * @throws InterruptedException */ protected void start() throws InterruptedException { logger.info("Starting NettyPerfClient"); reporter.start(); group = new NioEventLoopGroup(concurrency); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpClientCodec()).addLast(new ChunkedWriteHandler()) .addLast(new ResponseHandler()); } }); logger.info("Connecting to {}:{}", host, port); b.remoteAddress(host, port); perfClientStartTime = System.currentTimeMillis(); for (int i = 0; i < concurrency; i++) { b.connect().addListener(channelConnectListener); } isRunning = true; logger.info("Created {} channel(s)", concurrency); logger.info("NettyPerfClient started"); }
From source file:com.book.netty5.client.NettyClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO/*from w w w .j ava2 s .co m*/ 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 { ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler()); } }); // ?? ChannelFuture future = b.connect(new InetSocketAddress(host, port), new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync(); future.channel().closeFuture().sync(); } finally { // ???????? executor.execute(new Runnable() { public void run() { try { TimeUnit.SECONDS.sleep(1); try { connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ??? } catch (Exception e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } } }); } }
From source file:com.bow.demo.module.netty.demo.echo.EchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL.git final SslContext sslCtx; if (SSL) {//from w ww.java2 s. c o m sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } 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:com.bow.demo.module.netty.demo.echo.EchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {// ww w . jav a 2 s .com SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } 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:com.bow.demo.module.netty.demo.objectecho.ObjectEchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {// w ww . jav a 2s . c om 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 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 ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new ObjectEchoClientHandler()); } }); // Start the connection attempt. b.connect(HOST, PORT).sync().channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }
From source file:com.bow.demo.module.netty.demo.objectecho.ObjectEchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from w w w . j a v a 2s. co 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) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new ObjectEchoServerHandler()); } }); // Bind and start to accept incoming connections. b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.buildria.mocking.stub.StubHttpServer.java
License:Open Source License
@Override public StubHttpServer start() { Stopwatch sw = createStarted();// www .j a v a2s . c o m bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { // CHECKSTYLE:OFF @Override public void initChannel(SocketChannel ch) throws Exception { // CHECKSTYLE:ON // int maxInitialLineLength, int maxHeaderSize, int maxChunkSize ch.pipeline().addLast("decoder", new HttpRequestDecoder(MAX_INITIALLINE_LENGH, MAX_HEADERS_SIZE, MAX_CHUNK_SIZE)); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH)); ch.pipeline().addLast("encoder", new HttpResponseEncoder()); ch.pipeline().addLast("deflater", new HttpContentCompressor()); if (config.isLogging()) { ch.pipeline().addLast("logging", new LoggingHandler(StubHttpServer.class)); } ch.pipeline().addLast("handler", new Handler()); } }).option(ChannelOption.SO_BACKLOG, SO_BACKLOG).childOption(ChannelOption.SO_KEEPALIVE, true); // Bind and start to accept incoming connections. int port = config.getPort(); ChannelFuture f; try { f = b.bind(port).sync(); } catch (InterruptedException ex) { throw new MockingException(ex); } f.awaitUninterruptibly(); sw.stop(); LOG.debug("### StubHttpServer(port:{}) started. It took {}", port, sw); return this; }
From source file:com.caocao.nio.client.EchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {/* w ww. j a v a2s . com*/ 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(); p.addLast(new MsgDecoder()); p.addLast(new MsgEncoder()); p.addLast(new EchoClientHandler()); } }); // Start the client. ChannelFuture f = b.connect("127.0.0.1", 80).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }