网络通信框架——Netty示例

12 篇文章 0 订阅

网络通信框架——Netty示例

概述

  • Netty 是基于NIO封装的网络通信库,相较于Java原生IO库来说具有以下优点

    • API封装性好
    • 简单、易用
    • 功能强大,提供了各种常用库的接口
  • 推荐文章:https://segmentfault.com/a/1190000007282628

Netty 架构示意图

  • 服务端
    Netty 架构示意图
  • 客户端
    • 和服务端相似,但是只有一个EventLoopGroup,全部由它一个负责连接、数据处理。
  • 需要注意的点
    • BossGroup与WorkerGroup使用同一个EventLoopGroup,并都使用1个线程时,那么对应的是Reactor中的单线程模型
    • BossGroup使用1个线程,WorkerGroup使用多个线程时,那么对应的是Reactor中的多线程模型
    • Netty中并没实现Reactor中的主从多线程模型,即便BossGroup中可以传入多个线程的参数(实际只有一个线程在处理连接,其余的用于和其他ServerBootstrap共享时使用)
    • 推荐看一下:http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf

依赖

  • Maven依赖 pom.xml
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.43.Final</version>
    </dependency>
    
  • Gradle依赖 build.gradle
    compile 'io.netty:netty-all:4.1.43.Final'
    

Server/Client 简单示例

  • 使用最基础的ByteBuf进行传输
  • Netty 简单服务端示例
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Description: Netty 简单服务端示例
 * <br/>
 * Date: 2019/12/27 1:42
 *
 * @author ALion
 */
public class SimpleServer {

    public static void main(String[] args) {
        // linux 下建议使用 EpollEventLoopGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new SimpleServerHandler());
                    }
                });

        try {
            ChannelFuture future = bootstrap.bind(23333).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
  • Netty 简单服务器的处理器
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * Description: Netty 简单服务器的处理器
 * <br/>
 * Date: 2019/12/27 1:44
 *
 * @author ALion
 */
public class SimpleServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("SimpleServerHandler.channelRead");
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("Server received: " + buf.toString(CharsetUtil.UTF_8));

        ByteBuf byteBuf = Unpooled.copiedBuffer("happy", CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
    }

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

}
  • Netty 简单客户端示例
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

/**
 * Description: Netty 简单客户端示例
 * <br/>
 * Date: 2019/12/27 1:48
 *
 * @author ALion
 */
public class SimpleClient {

    public static void main(String[] args) {
        // linux 下建议使用 EpollEventLoopGroup
        EventLoopGroup loopGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap()
                .group(loopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new SimpleClientHandler());
                    }
                });

        try {
            ChannelFuture future = bootstrap.connect("127.0.0.1", 23333).sync();
            Channel channel = future.channel();

            Scanner scanner = new Scanner(System.in);
            for (int i = 0; i < 10; i++) {
                String s = scanner.nextLine();
                ByteBuf byteBuf = Unpooled.copiedBuffer(s, CharsetUtil.UTF_8);
                channel.writeAndFlush(byteBuf);
            }

            future.channel().close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            loopGroup.shutdownGracefully();
        }
    }

}
  • Netty 简单客户端的处理器
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * Description: Netty 简单客户端的处理器
 * <br/>
 * Date: 2019/12/27 1:50
 *
 * @author ALion
 */
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("SimpleClientHandler.channelRead");
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("Client received: " + buf.toString(CharsetUtil.UTF_8));
    }

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

Server/Client 聊天示例

  • 示例中展示了部分Netty提供的简化代码编写的API
  • Netty 聊天服务器示例
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;

/**
 * Description: Netty 聊天服务器示例
 * <br/>
 * Date: 2019/12/16 3:19
 *
 * @author ALion
 */
public class MyChatServer {

    public static void main(String[] args) {
        // linux 下建议使用 EpollEventLoopGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new MyChatServerInitializer());

        try {
            ChannelFuture future = serverBootstrap.bind(23333).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

}
  • Netty 聊天服务端的初始化器
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * Description: Netty 聊天服务端的初始化器
 * <br/>
 * Date: 2019/12/16 2:23
 *
 * @author ALion
 */
public class MyChatServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline()
                .addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()))
                .addLast(new StringDecoder(CharsetUtil.UTF_8))
                .addLast(new StringEncoder(CharsetUtil.UTF_8))
                .addLast(new MyChatServerHandler());
    }

}
  • Netty 聊天服务器的处理器
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * Description: Netty 聊天服务器的处理器
 * <br/>
 * Date: 2019/12/16 2:30
 *
 * @author ALion
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static final String SEPARATOR = System.lineSeparator();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyChatServerHandler.handlerAdded");

        Channel channel = ctx.channel();
        channelGroup.add(channel);
        channelGroup.writeAndFlush("Server> " + channel.remoteAddress() + " add" + SEPARATOR);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyChatServerHandler.channelActive");
        System.out.println(ctx.channel().remoteAddress() + " 连接");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("===========|" + channel.remoteAddress() + "> " + msg);

        for (Channel ch : channelGroup) {
            if (ch != channel) {
                ch.writeAndFlush(channel.remoteAddress() + "> " + msg + SEPARATOR);
            } else {
                ch.writeAndFlush("自己" + "> " + msg + SEPARATOR);
            }
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyChatServerHandler.channelInactive");
        System.out.println(ctx.channel().remoteAddress() + " 断开");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyChatServerHandler.handlerRemoved");

        Channel channel = ctx.channel();
        channelGroup.remove(channel); // Netty会自动寻找断掉的channel,然后移除,可以不用手动移除
        channelGroup.writeAndFlush("Server> " + channel.remoteAddress() + " remove" + SEPARATOR);
    }

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

}
  • Netty 聊天客户端示例
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

/**
 * Description: Netty 聊天客户端示例
 * <br/>
 * Date: 2019/12/16 2:41
 *
 * @author ALion
 */
public class MyChatClient {

    public static void main(String[] args) {
        // linux 下建议使用 EpollEventLoopGroup
        EventLoopGroup loopGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap()
                .group(loopGroup)
                .channel(NioSocketChannel.class)
                .handler(new MyChatClientInitializer());

        try {
            ChannelFuture future = bootstrap.connect("127.0.0.1", 23333).sync();
            Channel channel = future.channel();

            Scanner scanner = new Scanner(System.in);
            while (true) {
                String msg = scanner.nextLine();
                if ("exit".equals(msg)) break;
                channel.writeAndFlush(msg + System.lineSeparator());
            }

            channel.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            loopGroup.shutdownGracefully();
        }

    }

}
  • Netty 客户端的初始化器
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * Description: Netty 客户端的初始化器
 * <br/>
 * Date: 2019/12/16 2:44
 *
 * @author ALion
 */
public class MyChatClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline()
                .addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()))
                .addLast(new StringDecoder(CharsetUtil.UTF_8))
                .addLast(new StringEncoder(CharsetUtil.UTF_8))
                .addLast(new MyChatClientHandler());
    }

}
  • Netty 客户端的处理器
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Description: Netty 客户端的处理器
 * <br/>
 * Date: 2019/12/16 2:46
 *
 * @author ALion
 */
public class MyChatClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyClientHandler.channelActive");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//        Channel channel = ctx.channel();
        System.out.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
    
}
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值