io.netty.channel.ChannelInitializer Java Examples

The following examples show how to use io.netty.channel.ChannelInitializer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerRunner.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public ServerRunner(
      BridgeServerConfig serverConfig,
      InetSocketAddress socketBindAddress,
      ChannelInitializer<SocketChannel> channelInitializer,
      @Named("bossGroup") EventLoopGroup bossGroup,
      @Named("workerGroup") EventLoopGroup workerGroup,
      @Named("tcpChannelOptions") Map<ChannelOption<?>, Object> childChannelOptions,
      @Named("tcpParentChannelOptions") Map<ChannelOption<?>, Object> parentChannelOptions,
      @Named("bridgeEventLoopProvider") BridgeServerEventLoopProvider eventLoopProvider
) {
   this.serverConfig = serverConfig;
   this.socketBindAddress = socketBindAddress;
   this.channelInitializer = channelInitializer;
   this.bossGroup = bossGroup;
   this.workerGroup = workerGroup;
   this.childChannelOptions = childChannelOptions;
   this.parentChannelOptions = parentChannelOptions;
   this.eventLoopProvider = eventLoopProvider;
}
 
Example #2
Source File: TcpBroker.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private Channel tcpServer(int port) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(this.bossGroup, this.workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline channelPipeline = socketChannel.pipeline();
                    channelPipeline.addFirst("idle", new IdleStateHandler(
                            0,
                            0,
                            weEventConfig.getKeepAlive()));

                    //channelPipeline.addLast("ssl", getSslHandler(sslContext, socketChannel.alloc()));
                    channelPipeline.addLast("decoder", new MqttDecoder());
                    channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
                    channelPipeline.addLast("broker", new TcpHandler(protocolProcess));
                }
            });
    return serverBootstrap.bind(port).sync().channel();
}
 
Example #3
Source File: NettyTransportClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private Bootstrap initClientBootstrap() {
    Bootstrap b = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    b.group(eventLoopGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ClusterClientConfigManager.getConnectTimeout())
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                clientHandler = new TokenClientHandler(currentState, disconnectCallback);

                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
                pipeline.addLast(new NettyResponseDecoder());
                pipeline.addLast(new LengthFieldPrepender(2));
                pipeline.addLast(new NettyRequestEncoder());
                pipeline.addLast(clientHandler);
            }
        });

    return b;
}
 
Example #4
Source File: RxtxClient.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #5
Source File: ByteEchoPeerBase.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public void run() throws Exception {
    final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
            connectFactory, NioUdtProvider.BYTE_PROVIDER);
    try {
        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();
    }
}
 
Example #6
Source File: ServerModule.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
   // TODO this should be in an auth module
   bind(BridgeServerConfig.class);
   bind(BridgeServerTlsContext.class).to(BridgeServerTlsContextImpl.class);
   if(AUTHZ_LOADER_NONE.equals(algorithm)) {
      bind(BridgeServerTrustManagerFactory.class).to(NullTrustManagerFactoryImpl.class);
   }
   else {
      throw new IllegalArgumentException("Unrecognized authz loader class");
   }
   bind(new TypeLiteral<ChannelInitializer<SocketChannel>>(){})
      .to(Bridge10ChannelInitializer.class);

   bind(ServerRunner.class).asEagerSingleton();
}
 
Example #7
Source File: LocalTransportThreadModelTest3.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() {
    // Configure a test server
    group = new DefaultEventLoopGroup();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group)
            .channel(LocalServerChannel.class)
            .childHandler(new ChannelInitializer<LocalChannel>() {
                @Override
                public void initChannel(LocalChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            // Discard
                            ReferenceCountUtil.release(msg);
                        }
                    });
                }
            });

    localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
 
Example #8
Source File: ClusterAwareServerRunner.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public ClusterAwareServerRunner(
      BridgeServerConfig serverConfig,
      InetSocketAddress socketBindAddress,
      ChannelInitializer<SocketChannel> channelInitializer,
      @Named("bossGroup") EventLoopGroup bossGroup,
      @Named("workerGroup") EventLoopGroup workerGroup,
      @Named("tcpChannelOptions") Map<ChannelOption<?>, Object> childChannelOptions,
      @Named("tcpParentChannelOptions") Map<ChannelOption<?>, Object> parentChannelOptions,
      @Named("bridgeEventLoopProvider") BridgeServerEventLoopProvider eventLoopProvider
) {
   super(
         serverConfig,
         socketBindAddress,
         channelInitializer,
         bossGroup,
         workerGroup,
         childChannelOptions,
         parentChannelOptions,
         eventLoopProvider
   );
}
 
Example #9
Source File: StompClient.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new StompSubframeDecoder());
                pipeline.addLast("encoder", new StompSubframeEncoder());
                pipeline.addLast("aggregator", new StompSubframeAggregator(1048576));
                pipeline.addLast("handler", new StompClientHandler());
            }
        });

        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #10
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelHandler newServerHandler(final SslContext context,
        final byte[] response, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
                engine.setOcspResponse(response);
            }

            pipeline.addLast(sslHandler);

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
 
Example #11
Source File: VideoPreviewServerModule.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
   bind(BridgeServerConfig.class);
   bind(PreviewConfig.class);
   bind(BridgeServerTlsContext.class).to(BridgeServerTlsContextImpl.class);
   bind(BridgeServerTrustManagerFactory.class).to(NullTrustManagerFactoryImpl.class);
   bind(ChannelInboundHandler.class).toProvider(BaseWebSocketServerHandlerProvider.class);
   bind(new TypeLiteral<ChannelInitializer<SocketChannel>>(){}).to(HttpRequestInitializer.class);
   bind(Authenticator.class).to(ShiroAuthenticator.class);
   bind(SessionFactory.class).to(DefaultSessionFactoryImpl.class);
   bind(SessionRegistry.class).to(DefaultSessionRegistryImpl.class);
   bind(RequestMatcher.class).annotatedWith(Names.named("WebSocketUpgradeMatcher")).to(NeverMatcher.class);
   bind(RequestAuthorizer.class).annotatedWith(Names.named("SessionAuthorizer")).to(SessionAuth.class);
   bind(IrisNettyAuthorizationContextLoader.class).to(SubscriberAuthorizationContextLoader.class);

   // No Session Listeners
   Multibinder<SessionListener> slBindings = Multibinder.newSetBinder(binder(), SessionListener.class);

   // Bind Http Handlers
   Multibinder<RequestHandler> rhBindings = Multibinder.newSetBinder(binder(), RequestHandler.class);
   rhBindings.addBinding().to(RootRedirect.class);
   rhBindings.addBinding().to(IndexPage.class);
   rhBindings.addBinding().to(CheckPage.class);
   rhBindings.addBinding().to(PreviewHandler.class);
}
 
Example #12
Source File: CleartextHttp2ServerUpgradeHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void usedHttp2MultiplexCodec() throws Exception {
    final Http2MultiplexCodec http2Codec = new Http2MultiplexCodecBuilder(true, new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
        }
    }).build();
    UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {
        @Override
        public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            return new Http2ServerUpgradeCodec(http2Codec);
        }
    };
    http2ConnectionHandler = http2Codec;

    userEvents = new ArrayList<Object>();

    HttpServerCodec httpServerCodec = new HttpServerCodec();
    HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(httpServerCodec, upgradeCodecFactory);

    CleartextHttp2ServerUpgradeHandler handler = new CleartextHttp2ServerUpgradeHandler(
            httpServerCodec, upgradeHandler, http2Codec);
    channel = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            userEvents.add(evt);
        }
    });

    assertFalse(channel.writeInbound(Http2CodecUtil.connectionPrefaceBuf()));

    ByteBuf settingsFrame = settingsFrameBuf();

    assertTrue(channel.writeInbound(settingsFrame));

    assertEquals(1, userEvents.size());
    assertTrue(userEvents.get(0) instanceof PriorKnowledgeUpgradeEvent);
}
 
Example #13
Source File: UDTClientServerConnectionTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    final Bootstrap boot = new Bootstrap();
    final ThreadFactory clientFactory = new DefaultThreadFactory("client");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
            clientFactory, NioUdtProvider.BYTE_PROVIDER);
    try {
        boot.group(connectGroup)
                .channelFactory(NioUdtProvider.BYTE_CONNECTOR)
                .handler(new ChannelInitializer<UdtChannel>() {

                    @Override
                    protected void initChannel(final UdtChannel ch)
                            throws Exception {
                        final ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("framer",
                                new DelimiterBasedFrameDecoder(8192,
                                        Delimiters.lineDelimiter()));
                        pipeline.addLast("decoder", new StringDecoder(
                                CharsetUtil.UTF_8));
                        pipeline.addLast("encoder", new StringEncoder(
                                CharsetUtil.UTF_8));
                        pipeline.addLast("handler", new ClientHandler());
                    }
                });
        channel = boot.connect(address).sync().channel();
        isRunning = true;
        log.info("Client ready.");
        waitForRunning(false);
        log.info("Client closing...");
        channel.close().sync();
        isShutdown = true;
        log.info("Client is done.");
    } catch (final Throwable e) {
        log.error("Client failed.", e);
    } finally {
        connectGroup.shutdownGracefully().syncUninterruptibly();
    }
}
 
Example #14
Source File: ProxyToServerConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
@Override
        protected Future<?> execute() {
            Bootstrap cb = new Bootstrap().group(proxyServer.getProxyToServerWorkerFor(transportProtocol));

            switch (transportProtocol) {
            case TCP:
                LOG.debug("Connecting to server with TCP");
                cb.channelFactory(new ChannelFactory<Channel>() {
                    @Override
                    public Channel newChannel() {
                        return new NioSocketChannel();
                    }
                });
                break;
            case UDT:
                LOG.debug("Connecting to server with UDT");
//                cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
//                        .option(ChannelOption.SO_REUSEADDR, true);
//                break;
                throw new UnsupportedOperationException("unsupport udt proxy portocal");
            default:
                throw new UnknownTransportProtocolException(transportProtocol);
            }

            cb.handler(new ChannelInitializer<Channel>() {
                protected void initChannel(Channel ch) throws Exception {
                    initChannelPipeline(ch.pipeline(), initialRequest);
                };
            });
            cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    proxyServer.getConnectTimeout());

            if (localAddress != null) {
                return cb.connect(remoteAddress, localAddress);
            } else {
                return cb.connect(remoteAddress);
            }
        }
 
Example #15
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final long TIMEOUT = 2000;
    for (ChannelHandler h: clientHandlers) {
        if (h instanceof ProxyHandler) {
            ((ProxyHandler) h).setConnectTimeoutMillis(TIMEOUT);
        }
    }

    final FailureTestHandler testHandler = new FailureTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    ChannelFuture cf = b.connect(DESTINATION).channel().closeFuture();
    boolean finished = cf.await(TIMEOUT * 2, TimeUnit.MILLISECONDS);
    finished &= testHandler.latch.await(TIMEOUT * 2, TimeUnit.MILLISECONDS);

    logger.debug("Recorded exceptions: {}", testHandler.exceptions);

    assertProxyHandlers(false);

    assertThat(testHandler.exceptions.size(), is(1));
    Throwable e = testHandler.exceptions.poll();
    assertThat(e, is(instanceOf(ProxyConnectException.class)));
    assertThat(String.valueOf(e), containsString("timeout"));
    assertThat(finished, is(true));
}
 
Example #16
Source File: TestHttp.java    From netty-pubsub with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	EventLoopGroup bossGroup = new NioEventLoopGroup();
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	ServerBootstrap bootstrap = new ServerBootstrap();
	bootstrap.group(bossGroup, workerGroup)
	.option(ChannelOption.SO_BACKLOG, 1024)
	.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(65535));//�������Ϣת����һ��
			ch.pipeline().addLast("http-encoder",new HttpResponseEncoder());
			ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());//���������������
			ch.pipeline().addLast("http-server",new HttpHandler());
		}
	});
	
	try {
		ChannelFuture future = bootstrap.bind(8888).sync();
		future.channel().closeFuture().sync();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}finally {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
}
 
Example #17
Source File: PortUnificationServer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL context
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
        .build();

    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 {
                ch.pipeline().addLast(new PortUnificationServerHandler(sslCtx));
            }
        });

        // Bind and start to accept incoming connections.
        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #18
Source File: ProxyToServerConnection.java    From PowerTunnel with MIT License 5 votes vote down vote up
@Override
protected Future<?> execute() {
    Bootstrap cb = new Bootstrap()
            .group(proxyServer.getProxyToServerWorkerFor(transportProtocol))
            .resolver(remoteAddressResolver);

    switch (transportProtocol) {
        case TCP:
            LOG.debug("Connecting to server with TCP");
            cb.channelFactory(NioSocketChannel::new);
            break;
        case UDT:
            LOG.debug("Connecting to server with UDT");
            cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
                    .option(ChannelOption.SO_REUSEADDR, true);
            break;
        default:
            throw new UnknownTransportProtocolException(transportProtocol);
    }

    cb.handler(new ChannelInitializer<Channel>() {
        protected void initChannel(Channel ch) {
            initChannelPipeline(ch.pipeline(), initialRequest);
        }
    });
    cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            proxyServer.getConnectTimeout());

    if (localAddress != null) {
        return cb.connect(remoteAddress, localAddress);
    } else {
        return cb.connect(remoteAddress);
    }
}
 
Example #19
Source File: LocalChannelTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testReRegister() {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();

    cb.group(group1)
            .channel(LocalChannel.class)
            .handler(new TestHandler());

    sb.group(group2)
            .channel(LocalServerChannel.class)
            .childHandler(new ChannelInitializer<LocalChannel>() {
                @Override
                public void initChannel(LocalChannel ch) throws Exception {
                    ch.pipeline().addLast(new TestHandler());
                }
            });

    Channel sc = null;
    Channel cc = null;
    try {
        // Start server
        sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();

        // Connect to the server
        cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();

        cc.deregister().syncUninterruptibly();
    } finally {
        closeChannel(cc);
        closeChannel(sc);
    }
}
 
Example #20
Source File: EchoClient.java    From code with Apache License 2.0 5 votes vote down vote up
public void start(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            //1、创建 Bootstrap
            Bootstrap bootstrap = new Bootstrap();
            //2、指定 EventLoopGroup 以处理客户端事件;需要适用于 NIO 的实现
            bootstrap.group(group)
                    //3、适用于 NIO 传输的Channel 类型
                    .channel(NioSocketChannel.class)
                    //4、设置服务器的InetSocketAddress
                    .remoteAddress(new InetSocketAddress(host, port))
                    //5、在创建Channel时,向 ChannelPipeline中添加一个 EchoClientHandler实例
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            //6、连接到远程节点,阻塞等待直到连接完成
            ChannelFuture f = bootstrap.connect().sync();
            //7、阻塞,直到Channel 关闭
            f.channel().closeFuture().sync();
        } finally {
            //8、关闭线程池并且释放所有的资源
            group.shutdownGracefully().sync();
        }

    }
 
Example #21
Source File: EchoServer.java    From code with Apache License 2.0 5 votes vote down vote up
public void start(int port) throws Exception {
    //1、创建ChannelHandler和EventLoopGroup
    final EchoServerHandler serverHandler = new EchoServerHandler();
    EventLoopGroup group = new NioEventLoopGroup();
    //2、创建ServerBootstrap
    ServerBootstrap bootstrap = new ServerBootstrap();
    try {
        bootstrap.group(group)
                //3、指定所使用的 NIO传输 Channel
                .channel(NioServerSocketChannel.class)
                //4、使用指定的端口设置套接字地址
                .localAddress(new InetSocketAddress(port))
                //5、添加一个EchoServerHandler到子Channel的ChannelPipeline
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        //EchoServerHandler 被标注为@Shareable,所以我们可以总是使用同样的实例
                        //这里对于所有的客户端连接来说,都会使用同一个 EchoServerHandler,因为其被标注为@Sharable,
                        //这将在后面的章节中讲到。
                        ch.pipeline().addLast(serverHandler);
                    }
                });
        //6、异步地绑定服务器;调用 sync()方法阻塞等待直到绑定完成
        ChannelFuture cf = bootstrap.bind().sync();
        //7、获取 Channel 的CloseFuture,并且阻塞当前线程直到它完成
        cf.channel().closeFuture().sync();
    } finally {
        //8、关闭 EventLoopGroup,释放所有的资源
        group.shutdownGracefully().sync();
    }

}
 
Example #22
Source File: WsServer.java    From wind-im with Apache License 2.0 5 votes vote down vote up
public WsServer() {
	executor = new SimpleExecutor<Command, CommandResponse>();
	loadExecutor(executor);
	// 负责对外连接线程
	parentGroup = new NioEventLoopGroup();
	// 负责对内分发业务的线程
	childGroup = new NioEventLoopGroup();
	bootstrap = new ServerBootstrap();
	bootstrap.group(parentGroup, childGroup);
	bootstrap.channel(NioServerSocketChannel.class);
	bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			// 30秒空闲时间设置
			ch.pipeline().addLast(new IdleStateHandler(30, 0, 60));
			// HttpServerCodec:将请求和应答消息解码为HTTP消息
			ch.pipeline().addLast(new HttpServerCodec());
			// 针对大文件上传时,把 HttpMessage 和 HttpContent 聚合成一个
			// FullHttpRequest,并定义可以接受的数据大小64M(可以支持params+multipart)
			ch.pipeline().addLast(new HttpObjectAggregator(64 * 1024));
			// 针对大文件下发,分块写数据
			ch.pipeline().addLast(new ChunkedWriteHandler());
			// WebSocket 访问地址
			// ch.pipeline().addLast(new WebSocketServerProtocolHandler("/akaxin/ws"));
			// 自定义handler
			ch.pipeline().addLast(new WsServerHandler(executor));
		}
	});

}
 
Example #23
Source File: SimpleChannelPoolTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that if channel was unhealthy it is not offered back to the pool.
 *
 * @throws Exception
 */
@Test
public void testUnhealthyChannelIsNotOffered() throws Exception {
    EventLoopGroup group = new LocalEventLoopGroup();
    LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID);
    Bootstrap cb = new Bootstrap();
    cb.remoteAddress(addr);
    cb.group(group)
      .channel(LocalChannel.class);

    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group)
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelInitializer<LocalChannel>() {
          @Override
          public void initChannel(LocalChannel ch) throws Exception {
              ch.pipeline().addLast(new ChannelInboundHandlerAdapter());
          }
      });

    // Start server
    Channel sc = sb.bind(addr).syncUninterruptibly().channel();
    ChannelPoolHandler handler = new CountingChannelPoolHandler();
    ChannelPool pool = new SimpleChannelPool(cb, handler);
    Channel channel1 = pool.acquire().syncUninterruptibly().getNow();
    pool.release(channel1).syncUninterruptibly();
    Channel channel2 = pool.acquire().syncUninterruptibly().getNow();
    //first check that when returned healthy then it actually offered back to the pool.
    assertSame(channel1, channel2);

    channel1.close().syncUninterruptibly();

    pool.release(channel1).syncUninterruptibly();
    Channel channel3 = pool.acquire().syncUninterruptibly().getNow();
    //channel1 was not healthy anymore so it should not get acquired anymore.
    assertNotSame(channel1, channel3);
    sc.close().syncUninterruptibly();
    channel3.close().syncUninterruptibly();
    group.shutdownGracefully();
}
 
Example #24
Source File: HttpServer.java    From litchi with Apache License 2.0 5 votes vote down vote up
@Override
public void afterStart() {
    try {
        if (handlerList.isEmpty()) {
            throw new Exception("ChannelHandler is null");
        }

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                .option(ChannelOption.SO_BACKLOG, 12000).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline()
                                .addLast(new HttpServerCodec())
                                .addLast("aggregator", new HttpObjectAggregator(maxContentLength));
                        for (ChannelHandler handler : handlerList) {
                            ch.pipeline().addLast(handler);
                        }
                    }
                });

        b.bind(port);
        LOGGER.info("-----> connector started: http://127.0.0.1:{}/", port);
    } catch (Exception e) {
        LOGGER.error("{}", e);
    }
}
 
Example #25
Source File: DefaultTransportClient.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
protected ChannelHandler newChannelHandlerPipeline() {
    final CommandDispatcher commandDispatcher = new DefaultCommandDispatcher(requestBarrier, requestHandler, responseHandler);
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) {
            channel.pipeline()
                    .addLast(new NettyDecoder(codec))
                    .addLast(new NettyEncoder(codec))
                    .addLast(new ClientConnectionHandler())
                    .addLast(new TransportEventHandler(requestBarrier, transportEventBus))
                    .addLast(new CommandInvocation(commandDispatcher));
        }
    };
}
 
Example #26
Source File: WsServer.java    From openzaly with Apache License 2.0 5 votes vote down vote up
public WsServer() {
	executor = new SimpleExecutor<Command, CommandResponse>();
	loadExecutor(executor);
	// 负责对外连接线程
	parentGroup = new NioEventLoopGroup();
	// 负责对内分发业务的线程
	childGroup = new NioEventLoopGroup();
	bootstrap = new ServerBootstrap();
	bootstrap.group(parentGroup, childGroup);
	bootstrap.channel(NioServerSocketChannel.class);
	bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			// 30秒空闲时间设置
			ch.pipeline().addLast(new IdleStateHandler(30, 0, 60));
			// HttpServerCodec:将请求和应答消息解码为HTTP消息
			ch.pipeline().addLast(new HttpServerCodec());
			// 针对大文件上传时,把 HttpMessage 和 HttpContent 聚合成一个
			// FullHttpRequest,并定义可以接受的数据大小64M(可以支持params+multipart)
			ch.pipeline().addLast(new HttpObjectAggregator(64 * 1024));
			// 针对大文件下发,分块写数据
			ch.pipeline().addLast(new ChunkedWriteHandler());
			// WebSocket 访问地址
			// ch.pipeline().addLast(new WebSocketServerProtocolHandler("/akaxin/ws"));
			// 自定义handler
			ch.pipeline().addLast(new WsServerHandler(executor));
		}
	});

}
 
Example #27
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final SuccessTestHandler testHandler = new SuccessTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.AUTO_READ, ThreadLocalRandom.current().nextBoolean());
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    boolean finished = b.connect(destination).channel().closeFuture().await(10, TimeUnit.SECONDS);

    logger.debug("Received messages: {}", testHandler.received);

    if (testHandler.exceptions.isEmpty()) {
        logger.debug("No recorded exceptions on the client side.");
    } else {
        for (Throwable t : testHandler.exceptions) {
            logger.debug("Recorded exception on the client side: {}", t);
        }
    }

    assertProxyHandlers(true);

    assertThat(testHandler.received.toArray(), is(new Object[] { "0", "1", "2", "3" }));
    assertThat(testHandler.exceptions.toArray(), is(EmptyArrays.EMPTY_OBJECTS));
    assertThat(testHandler.eventCount, is(expectedEventCount));
    assertThat(finished, is(true));
}
 
Example #28
Source File: BrokerService.java    From iot-mqtt with Apache License 2.0 5 votes vote down vote up
private void startTcpServer(boolean useSsl, Integer port) {
	ServerBootstrap bootstrap = new ServerBootstrap();
	bootstrap.group(selectorGroup, ioGroup).channel(clazz)
			.option(ChannelOption.SO_BACKLOG, mqttConfig.getTcpBackLog())
			.childOption(ChannelOption.TCP_NODELAY, mqttConfig.isTcpNoDelay())
			.childOption(ChannelOption.SO_SNDBUF, mqttConfig.getTcpSndBuf())
			.option(ChannelOption.SO_RCVBUF, mqttConfig.getTcpRcvBuf())
			.option(ChannelOption.SO_REUSEADDR, mqttConfig.isTcpReuseAddr())
			.childOption(ChannelOption.SO_KEEPALIVE, mqttConfig.isTcpKeepAlive())
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel socketChannel) throws Exception {
					ChannelPipeline pipeline = socketChannel.pipeline();
					if (useSsl) {
						pipeline.addLast("ssl",
								NettySslHandler.getSslHandler(socketChannel, mqttConfig.isUseClientCA(),
										mqttConfig.getSslKeyStoreType(), mqttConfig.getSslKeyFilePath(),
										mqttConfig.getSslManagerPwd(), mqttConfig.getSslStorePwd()));
					}
					pipeline.addLast("idleStateHandler", new IdleStateHandler(60, 0, 0))
							.addLast("mqttEncoder", MqttEncoder.INSTANCE)
							.addLast("mqttDecoder", new MqttDecoder(mqttConfig.getMaxMsgSize()))
							.addLast("nettyConnectionManager", new NettyConnectHandler(brokerRoom.getNettyEventExcutor()))
							.addLast("nettyMqttHandler", new NettyMqttHandler());
				}
			});
	if (mqttConfig.isPooledByteBufAllocatorEnable()) {
		bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
	}
	try {
		bootstrap.bind(port).sync();
		log.info("[Server] -> start tcp server {} success,port = {}", useSsl ? "with ssl" : "", port);
	} catch (InterruptedException ex) {
		log.error("[Server] -> start tcp server {} failure.cause={}", useSsl ? "with ssl" : "", ex);
	}
}
 
Example #29
Source File: VideoPreviewUploadServerModule.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
   bind(BridgeServerConfig.class);
   bind(TrustConfig.class);
   bind(PreviewConfig.class);
   bind(HubSessionListener.class).to(NoopHubSessionListener.class);
   bind(SessionFactory.class).to(HubSessionFactory.class);
   bind(SessionRegistry.class).to(DefaultSessionRegistryImpl.class);
   bind(ClientFactory.class).to(VideoPreviewUploadClientFactory.class);

   bind(BridgeServerTlsContext.class).to(BridgeServerTlsContextImpl.class);
   bind(BridgeServerTrustManagerFactory.class).to(HubTrustManagerFactoryImpl.class);
   bind(new TypeLiteral<ChannelInitializer<SocketChannel>>(){}).to(HttpRequestInitializer.class);

   bind(ChannelInboundHandler.class).toProvider(BaseWebSocketServerHandlerProvider.class);
   bind(RequestMatcher.class).annotatedWith(Names.named("WebSocketUpgradeMatcher")).to(NeverMatcher.class);
   bind(RequestAuthorizer.class).annotatedWith(Names.named("SessionAuthorizer")).to(AlwaysAllow.class);

   bind(VideoPreviewUploadServerConfig.class);

   // No Session Listeners
   Multibinder<SessionListener> slBindings = Multibinder.newSetBinder(binder(), SessionListener.class);

   // Bind Http Handlers
   Multibinder<RequestHandler> rhBindings = Multibinder.newSetBinder(binder(), RequestHandler.class);
   rhBindings.addBinding().to(RootRedirect.class);
   rhBindings.addBinding().to(CheckPage.class);
   rhBindings.addBinding().to(IndexPage.class);
   rhBindings.addBinding().to(UploadHandler.class);
}
 
Example #30
Source File: VideoStreamingServerModule.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
   bind(BridgeServerConfig.class);
   bind(VideoStreamingServerConfig.class);

   bind(BridgeServerTlsContext.class).to(BridgeServerTlsContextImpl.class);
   bind(BridgeServerTrustManagerFactory.class).to(NullTrustManagerFactoryImpl.class);

   bind(SessionFactory.class).to(NullSessionFactoryImpl.class);
   bind(SessionRegistry.class).to(NullSessionRegistryImpl.class);
   bind(ClientFactory.class).to(VideoStreamingClientFactory.class);

   bind(ChannelInboundHandler.class).toProvider(BaseWebSocketServerHandlerProvider.class);
   bind(new TypeLiteral<ChannelInitializer<SocketChannel>>(){}).to(HttpRequestInitializer.class);

   bind(RequestMatcher.class).annotatedWith(Names.named("WebSocketUpgradeMatcher")).to(NeverMatcher.class);
   bind(RequestAuthorizer.class).annotatedWith(Names.named("SessionAuthorizer")).to(AlwaysAllow.class);

   // No Session Listeners
   Multibinder<SessionListener> slBindings = Multibinder.newSetBinder(binder(), SessionListener.class);

   // Bind Http Handlers
   Multibinder<RequestHandler> rhBindings = Multibinder.newSetBinder(binder(), RequestHandler.class);
   rhBindings.addBinding().to(CheckPage.class);
   rhBindings.addBinding().to(HlsHandler.class);
   rhBindings.addBinding().to(HlsPlaylistHandler.class);
   rhBindings.addBinding().to(HlsIFrameHandler.class);
   rhBindings.addBinding().to(HlsVideoHandler.class);
   rhBindings.addBinding().to(JPGHandler.class);

   if (dash) {         
      rhBindings.addBinding().to(DashVideoHandler.class);
   }
}