List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:com.example.discard.DiscardServerMain.java
License:Apache License
public void run() throws Exception { final NioEventLoopGroup bossGroup = new NioEventLoopGroup();//1 final NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try (AutoCloseable ignore = new ShutDownGracefully(bossGroup, workerGroup)) { final ServerBootstrap bootstrap = new ServerBootstrap();//2 bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)//3 .childHandler(new ChannelInitializer<SocketChannel>() {//4 @Override//from www . j a v a 2 s . c o m protected void initChannel(final SocketChannel ch) { ch.pipeline().addLast(new DiscardServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 128)//5 .childOption(ChannelOption.SO_KEEPALIVE, true); //6 final ChannelFuture channelFuture = bootstrap.bind(port).sync();//7 channelFuture.channel().closeFuture().sync(); } }
From source file:com.example.grpc.server.PrometheusServer.java
License:Apache License
public void start() { final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override/* ww w.j av a 2 s .c om*/ protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("prometheus", new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception { if (!(o instanceof HttpRequest)) { return; } HttpRequest request = (HttpRequest) o; if (!"/metrics".equals(request.uri())) { final FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); return; } if (!HttpMethod.GET.equals(request.method())) { final FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_ACCEPTABLE); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); return; } ByteBuf buf = Unpooled.buffer(); ByteBufOutputStream os = new ByteBufOutputStream(buf); OutputStreamWriter writer = new OutputStreamWriter(os); TextFormat.write004(writer, registry.metricFamilySamples()); writer.close(); os.close(); final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); } }); } }); try { this.channel = bootstrap.bind(this.port).sync().channel(); } catch (InterruptedException e) { // do nothing } }
From source file:com.example.server.ServerChannelInitializationConfigurer.java
License:Apache License
static ChannelInitializer<SocketChannel> applyConfigurer( final Iterable<ServerChannelInitializationConfigurer> configurers) { final Logger log = LoggerFactory.getLogger(ServerChannelInitializationConfigurer.class); final ImmutableList<ServerChannelInitializationConfigurer> list = Lists.immutable.ofAll(configurers); log.info("configurers: {}", list); return new ChannelInitializer<SocketChannel>() { @Override//from ww w . ja v a2s .c o m protected void initChannel(final SocketChannel ch) { log.info("initialize: {}", list); list.injectInto(ch.pipeline(), (pip, config) -> pip.addLast(config.channelHandler())); } }; }
From source file:com.example.spring.boot.netty.TcpClient.java
License:Apache License
public void connectServer() { for (int i = 0; i < connNum; i++) { EventLoopGroup group = new NioEventLoopGroup(); try {/* w ww . j a va 2 s .c o m*/ 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 LoggingHandler(LogLevel.INFO)); p.addLast(new LineBasedFrameDecoder(1024)); p.addLast(new StringDecoder()); p.addLast(new TcpClientHandler(TcpClient.this)); } }); // Start the client. ChannelFuture f = b.connect(address.split(":")[0], Integer.parseInt(address.split(":")[1])).sync(); // Wait until the connection is closed. // f.channel().closeFuture().sync(); } catch (Throwable e) { e.printStackTrace(); } finally { // Shut down the event loop to terminate all threads. // group.shutdownGracefully(); } } }
From source file:com.example.spring.boot.netty.TcpServer.java
License:Apache License
public void bind() { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from ww w . j a v a 2 s . c o m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 65535).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new LineBasedFrameDecoder(1024)); p.addLast(new StringDecoder()); p.addLast(TCP_SERVER_HANDLER); } }); // Start the server. ChannelFuture f = b.bind(port).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } catch (Throwable e) { e.printStackTrace(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.fanavard.challenge.client.websocket.WebSocketClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;/*w w w. j a v a2 s .c om*/ } else if ("https".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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } 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 WebSocketClientHandler handler = new WebSocketClientHandler(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), new WebSocketClientCompressionHandler(), 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:com.farsunset.cim.sdk.android.CIMConnectorManager.java
License:Apache License
private CIMConnectorManager(Context ctx) { context = ctx;//w ww . j av a 2 s . co m bootstrap = new Bootstrap(); loopGroup = new NioEventLoopGroup(1); bootstrap.group(loopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ClientMessageDecoder()); ch.pipeline().addLast(new ClientMessageEncoder()); ch.pipeline().addLast(new IdleStateHandler(READ_IDLE_TIME, 0, 0)); ch.pipeline().addLast(CIMLoggingHandler.getLogger()); ch.pipeline().addLast(CIMConnectorManager.this); } }); }
From source file:com.farsunset.cim.sdk.client.CIMConnectorManager.java
License:Apache License
private CIMConnectorManager() { bootstrap = new Bootstrap(); loopGroup = new NioEventLoopGroup(); bootstrap.group(loopGroup);/*w w w.ja va 2s . c o m*/ bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ClientMessageDecoder()); pipeline.addLast(new ClientMessageEncoder()); pipeline.addLast(new IdleStateHandler(READ_IDLE_TIME, 0, 0)); pipeline.addLast(CIMConnectorManager.this); } }); }
From source file:com.farsunset.cim.sdk.server.handler.CIMNioSocketAcceptor.java
License:Apache License
public void bind() throws IOException { /**/*from w w w . j a v a 2 s . com*/ * websocket?? */ innerHandlerMap.put(WEBSOCKET_HANDLER_KEY, new WebsocketHandler()); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()); bootstrap.childOption(ChannelOption.TCP_NODELAY, true); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ServerMessageDecoder()); ch.pipeline().addLast(new ServerMessageEncoder()); ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO)); ch.pipeline().addLast(new IdleStateHandler(READ_IDLE_TIME, WRITE_IDLE_TIME, 0)); ch.pipeline().addLast(CIMNioSocketAcceptor.this); } }); bootstrap.bind(port); }
From source file:com.feihong.newzxclient.tcp.NettyClient.java
License:Apache License
@SuppressWarnings("unchecked") public void connect() throws Exception { mGroup = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(mGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override/* w w w . java2 s.co m*/ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("decoder", new IntLengthDecoder()); ch.pipeline().addLast(new NettyClientHandler()); } }); ChannelFuture future = b.connect(host, port).sync(); future.addListeners(new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { requestLogin(); } }); mChannel = future.channel(); mHandler = mChannel.pipeline().get(NettyClientHandler.class); }