Netty 笔记

Netty 核心组件

  • Channel
  • 回调
  • Future
  • 事件和ChannelHandler

Channel

Channel 是 Java NIO 的一个基本构造,可以把它看作是传入或者传出数据的载体(通道),因此可以被打开或者关闭。

回调

回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。

Netty 在内部是通过回调来处理事件;当事件发生时,Netty会回调用实现了 interface-ChannelHandler 的函数处理该事件。

Future

Future用于表示异步操作的结果,每个Netty 的出战 I/O 操作都会返回一个 ChannelFuture。

事件和 ChannelHandler

Netty 使用不同的事件来通知我们状态的改变或者操作的状态,我们可以通过发生的事件来触发相对于的动作。

发生的每个事件都会被分发给 ChannelHander 类中的某个使用户实现的方法。大部分情况我们都需要自己实现 ChannelHandler 然后通过通过重写方法实现自己的业务逻辑。

基于 Netty 的服务器和客户端

要做的很简单,就是:客户端发送消息给服务器,然后服务器接收客户端发动的消息并回复一条消息给客户端。

Netty 依赖

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

服务器

基于 Neety 的服务器需要两部分:

  • ChannelHandler 实现类,我们需要通过实现它来接收客服端的数据(业务逻辑)
  • 引导——服务器配置及启动代码(配置)
ChannelHandler 实现
package com.project.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;


@Sharable // 标识 Channel-Handler 可以被多个 Channel 安全共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    
    // 读取客服端消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 读取消息
        ByteBuf in = (ByteBuf) msg;
        System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));
        
        // 将消息写给发送者, 并不发送,需要调用 flush 方法才会发送
        ctx.write(Unpooled.copiedBuffer("你好!", CharsetUtil.UTF_8));
    }
    
    // 一条消息读取完成(一条消息可能需要多次读取)时调用
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 将消息发送给客服端,并关闭该 Channel
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
            .addListener(ChannelFutureListener.CLOSE);
    }
    
    // 在读取消息期间,发生异常时调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        
        cause.printStackTrace();
        ctx.close();
    }
}

上面代码中,我们继承一个ChannelHandler的实现类 ChannelInboundHandlerAdapter

引导

ChannelHander 写好了,我还还需要做以下工作才能使服务器工作:

  • 设置监听端口
  • 配置 Channel,使入站消息发送给我们刚刚编写的 EchoServerHandler 处理。
package com.project.demo;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
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.nio.NioServerSocketChannel;


/**
 * 1. 创建一个ServerBootstrap的实例以引导和绑定服务器
 * 2. 创建并分配一个NioEventLoopGroup实例以进行事件的处理
 * 3. 指定服务器绑定的本地的InetSocketAddress
 */
public class EchoServer {

    private int port;
    
    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        // 消息处理器实例
        final EchoServerHandler serverHandler = new EchoServerHandler();
        // Nio
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            // 配置
            b.group(group)
                .channel(NioServerSocketChannel.class)  // 指定使用的 NIO 
                .localAddress(new InetSocketAddress(port))  // 指定端口
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        // 注册自定义的 ChannelHandle 使之生效
                        ch.pipeline().addLast(serverHandler);
                    }
                });
            // 绑定服务器
            ChannelFuture f = b.bind().sync();
            // 获取 channel 的 CloseFuture
            f.channel().closeFuture().sync();
        } finally {
            // 关闭EventLoopGroup,释放所有的资源
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new EchoServer(8081).start();  // 启动
    }
}

客户端

客服端同服务器一样也需要编写两个部分的代码,ChannelHandler实现(业务逻辑)和引导(配置和启动)

ChannelHandler实现
package com.project.demo;

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

// 客户端消息处理器
@Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    
    // 接收数据时被调用
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("Chient received: " + msg.toString(CharsetUtil.UTF_8));
    }
    
    // 建立时被调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
       // 发送消息到服务器
       ctx.writeAndFlush(Unpooled.copiedBuffer("Hello!", CharsetUtil.UTF_8));
    }
    
    // 处理过程中发生异常时被调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       cause.printStackTrace();
       // 关闭 Channel
       ctx.close();
    }
}
引导

客户端的引导需要指定主机及端口

package com.project.demo;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
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;
/**
 * 1. 创建了一个Bootstrap实例
 * 2. 为进行事件处理分配了一个NioEventLoopGroup实例
 * 3. 为服务器连接创建了一个InetSocketAddress实例
 * 4. 当连接建立时,EchoClientHandle 实例会被安装到 ChannelPipeline 中
 * 5. 配置完成后,通过调用Bootstrap.connect()方法连接到远程节点(服务器)
 */
public class EchoClient {

    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(host, port))  // 指定 host,port
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });
            // 连接到远程节点,阻塞等待直到连接完成
            ChannelFuture f = b.connect().sync();
            // 阻塞,直到 Channel 关闭
            f.channel().closeFuture().sync();
        } finally {
            // 关闭连接次并释放资源
            group.shutdownGracefully().sync();
        }
    }
    
    public static void main(String[] args) throws Exception {
        new EchoClient("127.0.0.1", 8081).start();
    }
}

到这里这个基于 Netty 的简单程序就编写完了,想测试是否成功可以先启动 EchoServer 然后再启动 EchoClient,客户端启动会发送一条 Hello 给服务器,服务器接收到消息后会回复 你好 给客户端。

Netty 常用组件

Netty网络抽象的代表:

  • Channel——Socket;
  • EventLoop——控制流、多线程处理、并发;
  • ChannelFuture——异步通知。
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,701评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,649评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,037评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,994评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,018评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,796评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,481评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,370评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,868评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,014评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,153评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,832评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,494评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,039评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,437评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,131评论 2 356

推荐阅读更多精彩内容