前言
在实际开发中,server端接收数据后我们希望他是一个字符串或者是一个对象类型,而不是字节码,那么;
在netty中是否可以自动的把接收的Bytebuf数据转String,不需要我手动处理? 答;有,可以在管道中添加一个StringDecoder。
在网络传输过程中有半包粘包的问题,netty能解决吗? 答:能,netty提供了很丰富的解码器,在正确合理的使用下就能解决半包粘包问题。
常用的String字符串下有什么样的解码器呢? 答:不仅在String下有处理半包粘包的解码器在处理其他的数据格式也有,其中谷歌的protobuf数据格式就是其中一个。对于String的有以下常用的三种:
A:LineBasedFrameDecoder 基于换行
B:DelimiterBasedFrameDecoder 基于指定字符串
C:FixedLengthFrameDecoder 基于字符串长度
新建
MyChannelInitializer
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel channel) {
/* 解码器 */
// 基于换行符号
channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
// 基于指定字符串【换行符,这样功能等同于LineBasedFrameDecoder】
// e.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, false, Delimiters.lineDelimiter()));
// 基于最大长度
// e.pipeline().addLast(new FixedLengthFrameDecoder(4));
// 解码转String,注意调整自己的编码格式GBK、UTF-8
channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
//在管道中添加我们自己的接收数据实现方法
channel.pipeline().addLast(new MyServerHandler());
}
}
public class MyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
System.out.println("链接报告开始 {关注明哥 >获取学习源码}");
System.out.println("链接报告信息:有一客户端链接到本服务端");
System.out.println("链接报告IP:" + channel.localAddress().getHostString());
System.out.println("链接报告Port:" + channel.localAddress().getPort());
System.out.println("链接报告完毕");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
//接收msg消息{与上一章节相比,此处已经不需要自己进行解码}
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 接收到消息:" + msg);
}
}
public class NettyServer {
public static void main(String[] args) {
new NettyServer().bing(7397);
}
private void bing(int port) {
//配置服务端NIO线程组
EventLoopGroup parentGroup = new NioEventLoopGroup(); //NioEventLoopGroup extends MultithreadEventLoopGroup Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class) //非阻塞模式
.option(ChannelOption.SO_BACKLOG, 128)
.childHandler(new MyChannelInitializer());
ChannelFuture f = b.bind(port).sync();
System.out.println("com.lm.netty04 server start done. {关注码农明哥:获取源码}");
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
childGroup.shutdownGracefully();
parentGroup.shutdownGracefully();
}
}
}
启动nettyServer进行测试
好了到这里就结束了基础netty之NettyServer字符串解码器 的学习,大家一定要跟着动手操作起来。需要的源码的 可si我获取;