Netty(下)

本文深入探讨了Netty中Google Protobuf的使用,包括编解码器介绍、快速入门案例,以及Netty的handler调用机制。同时,文章详细分析了TCP粘包和拆包问题,提供了案例演示和解决方案。

1、Google Protobuf

1.1、编解码器基本介绍

1.2、Netty本身编解码器机制及问题分析

1.3、Protobuf

1.4、Protobuf快速入门案例

1.4.1、Student.proto

syntax="proto3";
option java_outer_classname = "StudentPOJO";//生成的外部类名,同时也是文件名
//protobuf 使用message 管理数据
message Student{//会在外部类 StudentPOJO 里生成一个内部类 Student 它是真正发送的pojo对象
  int32 id = 1;//Student 类中有一个属性 名字为 id 类型为 int32(protobuf类型)1 表示属性序号,不是值
  string name = 2;
}

1.4.2、生成StudentPOJO.java

进入cmd命令行

protoc.exe --java_out=. Student.proto

将生成的java文件拷过去即可

1.4.3、Handler及编解码器

client

client handler

server

server handler

1.4.2、项目截图

2、Netty编解码器以及handler的调用机制

2.1、基本说明

2.2、编解码器

2.3、解码器 ByteToMessageDecoder

2.4、handler的调用机制

2.5、ReplayingDecoder解码器

/**
 * @author wzcstart
 * @date 2021/7/3 - 13:35
 */
public class MyByteToLongDecoder2 extends ReplayingDecoder<Void> {//使用void表示无状态控制
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("MyByteToLongDecoder2 decode 被调用");
        //在 ReplayingDecoder 中不需要进行判读是否足够转换,内部会自行判断
        out.add(in.readLong());
    }
}

2.6、其他编解码器

2.6.1、其他解码器

2.6.2、其他编码器

3、TCP 粘包及拆包问题及解决方案

TCP粘包和拆包主要是因为TCP为了更有效的将信息传送给对方,TCP使用Nagle算法优化,将多次间隔较小且数据量小的数据合并成一个大数据块,然后进行封包

主要解决应用层读取数据长度问题

3.1、TCP粘包及拆包基本介绍

3.2、TCP粘包拆包案例演示

粘包现象

本来发送10条消息,结果第一次合并为了一条,第二次按照四次完成

处理器代码

3.2.1、MyClientHandler

/**
 * @author wzcstart
 * @date 2021/7/3 - 22:46
 */
public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        System.out.println("客户端接收消息:"+new String(bytes, StandardCharsets.UTF_8));
        System.out.println("客户端接收总数:"+(++count));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //连接建立后发送10个消息
        for (int i = 0; i < 10; i++) {
            ByteBuf buf = Unpooled.copiedBuffer("hello,server " + i, CharsetUtil.UTF_8);
            ctx.writeAndFlush(buf);
        }
    }
}

3.2.2、MyServerHandler

/**
 * @author wzcstart
 * @date 2021/7/3 - 22:46
 */
public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        //接受消息
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        System.out.println("服务端接收消息:"+new String(bytes, StandardCharsets.UTF_8));
        System.out.println("服务端接收总数:"+(++count));
        //发送消息
        ctx.writeAndFlush(Unpooled.copiedBuffer(UUID.randomUUID().toString()+"\n",StandardCharsets.UTF_8));
    }


}

3.3、TCP粘包及拆包解决方案

关键是读取数据长度问题

具体案例

MessageProtocol

/**
 * @author wzcstart
 * @date 2021/7/3 - 23:51
 */
@Data
@AllArgsConstructor
public class MessageProtocol {
    private int length;
    private byte[] content;
}

4、源码分析

参考netty ppt

### 如何在 Netty 框架中实现 WebSocket 功能 #### 创建 WebSocket 服务器类 为了创建一个简单的 WebSocket 服务器,可以定义一个新的 Java 类 `WebSocketServer` 来初始化并启动服务器实例。此过程涉及设置事件循环组、绑定端口以及指定通道处理器。 ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class WebSocketServer { private final int port; public WebSocketServer(int port) { this.port = port; } public void start() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new WebSocketInitializer()); ChannelFuture f = b.bind(port).sync(); System.out.println("WebSocket server started at ws://localhost:" + port); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` #### 配置 WebSocket 初始化器 为了让服务器能够处理 WebSocket 请求,还需要编写自定义的 `ChannelInitializer` 子类来配置管道中的编解码器和其他必要的处理器。这一步骤通过继承 `ChannelInitializer<SocketChannel>` 并重写其方法完成。 ```java import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; class WebSocketInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // 添加HTTP支持所需的编码/解码器 pipeline.addLast(new HttpServerCodec()); // 支持大文件传输 pipeline.addLast(new ChunkedWriteHandler()); // 聚合HTTP消息片段成完整的请求对象 pipeline.addLast(new HttpObjectAggregator(65536)); // 处理WebSocket协议握手及后续帧交换逻辑 String websocketPath = "/websocket"; pipeline.addLast(new WebSocketServerProtocolHandler(websocketPath)); // 自定义业务逻辑处理器 pipeline.addLast(new WebSocketFrameHandler()); } } ``` #### 实现 WebSocket 帧处理器 最后,需要定义具体的业务逻辑处理器用于响应来自客户端的消息或其他交互操作。这里展示了一个基本的例子——每当接收到一条新消息时都会打印出来,并且回显给发送者。 ```java import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; public class WebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { // 打印接收的信息 System.out.println("Received message from client: " + msg.text()); // 向客户端回送相同的内容 ctx.writeAndFlush(new TextWebSocketFrame("Echo: " + msg.text())); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // 当有新的连接建立时触发 System.out.println("New connection established."); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 以上代码展示了如何利用 Netty 构建一个基础版的支持 WebSocket 协议的服务端应用[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值