下面列出了怎么用 io.netty.handler.codec.FixedLengthFrameDecoder 的API类实例代码及写法,或者点击链接到github查看源代码。
public void connect(String host, int port) throws InterruptedException {
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
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new FixedLengthFrameDecoder(1<<5));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture future = b.connect(host, port).sync();
future.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
public void bind(int port) throws InterruptedException {
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
protected void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new FixedLengthFrameDecoder(1<<5));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new ServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
//等待服务器退出
f.channel().closeFuture().sync();
} finally {
//释放线程资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
@Provides
@HealthCheckProtocol
static ImmutableList<Provider<? extends ChannelHandler>> provideHandlerProviders(
Provider<FixedLengthFrameDecoder> fixedLengthFrameDecoderProvider,
Provider<HealthCheckHandler> healthCheckHandlerProvider) {
return ImmutableList.of(fixedLengthFrameDecoderProvider, healthCheckHandlerProvider);
}
@Provides
static FixedLengthFrameDecoder provideFixedLengthFrameDecoder(ProxyConfig config) {
return new FixedLengthFrameDecoder(config.healthCheck.checkRequest.length());
}