Netty框架构建Nio编程

~~~ 随手点赞,养成习惯 ~~~

为什么选择Netty框架

Netty是业界最流行的NIO框架之一,它的健壮性、功能、性能、可定制性和可扩展性在同类框架中都是首屈一指的。
优点:
① API使用简单,开发门槛低
②功能强大,预置了多种编解码功能,支持多种主流协议
③ 定制能力强,可以通过ChannelHandler对通信框架进行灵活地扩展;
④性能高,通过与其他业界主流的NIO框架对比,Netty的综合性能最优;
⑤成熟、稳定,Netty修复了已经发现的所有JDK NIO BUG,业务开发人员不需要再为NIO的BUG而烦恼;
这些优点Netty逐渐成为了Java NIO编程的首选框架。

Netty版本介绍

最新版本已到5.0,但目前用4.x较多,

在这里插入图片描述

Netty粘包,拆包

主要演示如何拆包、粘包的。代码编写和最后如何解决。

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.42.Final</version>
</dependency>

画图真耽误时间


服务端代码 演示粘包、拆包

package com.amt.server;

import com.mayikt.server.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @title:NettyServer
 * @description: 服务端
 * @author: liuy
 * @data 2020/7/26 12:06
 */
public class NettyServer {
    private static int port = 8080;
    public static void main (String[] args){
        // 使用netty创建我们的服务器端的时候 采用两个线程池,
        //为什么是两个线程池看上图。
        //负责接受我们的请求的线程池
        NioEventLoopGroup receptionGroup = new NioEventLoopGroup();
        //处理工作的线程池处理我们请求读写操作
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        // 创建我们的serverBootstrap
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(receptionGroup,workGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
      //socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        //socketChannel.pipeline().addLast(new StringEncoder()); 
   		 socketChannel.pipeline().addLast(new ServerHandler());
                    }
                });

        try {
            // 绑定端口号
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("服务器端启动成功:" + port);
            //等待监听我们的请求
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {

        } finally {
            //关闭线程池
            receptionGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}

package com.amt.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @title:ServerHandler
 * @description:
 * @author: liuy
 * @data 2020/7/26 12:30
 */
public class ServerHandler extends SimpleChannelInboundHandler {

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        //ByteBuf 是对原生NIO中ByteBuffer封装
        ByteBuf byteBuf = (ByteBuf) msg;
        String request = byteBuf.toString(CharsetUtil.UTF_8);
        System.out.println("request:" + request);
        // 响应代码
        channelHandlerContext.writeAndFlush((Unpooled.copiedBuffer("服务端已收到消息!", CharsetUtil.UTF_8)));
    }


}

客户端

package com.amt.client;

import com.amt.client.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class NettyClient {
    public static void main(String[] args) {
        //创建nioEventLoopGroup
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        // 服务端是NioServerSocketChannel.class   这里是NioSocketChannel.class
        //NioServerSocketChannel 这里是NioSocketChannel的区别在于 前者是管理所有客户端的channel
        bootstrap.group(group).channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress("127.0.0.1", 8080))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 处理每个请求hanlder
                        ch.pipeline().addLast(new ClientHandler());
                    }
                });
        try {
            // 发起同步连接
            ChannelFuture sync = bootstrap.connect().sync();
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }
}

package com.amt.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author: liuy
 * @data 2020/7/26 12:06
 */
public class ClientHandler extends SimpleChannelInboundHandler {
    /**
     * 活跃的通道
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 10; i++) {
            ctx.writeAndFlush((Unpooled.copiedBuffer("收到请答复", CharsetUtil.UTF_8)));
        }
        // 我们现在客户端发送10条消息,那么我们客户端也要收到这10条消息
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        String resp = byteBuf.toString(CharsetUtil.UTF_8);
        System.out.println("服务端回信:" + resp);
    }
}

在这里插入图片描述
在这里插入图片描述
粘包现象:客户端发送了10次 ,服务端应该收到10次。服务端确将收到的10次信息合并了。 原理 是服务端将缓冲区 Buffer中的信息一次性读取出来了。 (客户端送了10滴水,服务端想喝水是将10滴水先放在水杯中再喝。 )所以我们看到信息 (收到请答复收到请答复收到请答复) 粘连在一起了。。。。客户端收到服务端10次才对,现只有收到一次(“服务端回信:服务端收到信息!”)
在这里插入图片描述
拆包 :如果客户端发送的信息 超过了缓冲区设置的大小,那么会出现拆包现象, 例如:客户端发送两次信息 Msg Msg,服务端收到 Ms, gMsg 这样

如何解决拆包、粘包

解决思路:
1.以固定的长度发送数据,到缓冲区 (这种不科学但是一种思路嘛)
2.可以在数据之间设置一些边界(\n或者\r\n)

现说2这种思路: 客户端循环10次发送的信息 “收到请答复” 修改为“收到请答复\n”

 for (int i = 0; i < 10; i++) {
            ctx.writeAndFlush((Unpooled.copiedBuffer("收到请答复\n", CharsetUtil.UTF_8)));
        }

服务端收到信息 按\n切割为数组 ,如下:

		String[] split = request.split("\n");
        for(int i = 0;i<split.length;i++){
            System.out.println("split:" + split[i]);
        }

可利用编码器LineBaseDFrameDecoder解决tcp粘包的问题
上面这种方式比较low 写的目的只要是提供思路 引入编码器

此解码器提供了对数据设置边界 \n \r\n
解码器 和 上面的思路一样

//服务端和客户端放开下面代码的注释
socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
socketChannel.pipeline().addLast(new StringEncoder());

客户端和服务端发送信息 都在信息后加上\n

为了显示出思路,没有一上来就提供完整的代码。 若有不足的地方吐槽评论在完善。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值