netty简介及使用

来源:互联网 发布:淘宝曼哈顿直通车真假 编辑:程序博客网 时间:2024/06/12 01:22

netty简介

Netty是一个高性能、异步事件驱动的NIO框架,它提供了对TCP、UDP和文件传输的支持,作为一个异步NIO框架,Netty的所有IO操作都是异步非阻塞的,通过Future-Listener机制,用户可以方便的主动获取或者通过通知机制获得IO操作结果。

作为当前最流行的NIO框架,Netty在互联网领域、大数据分布式计算领域、游戏行业、通信行业等获得了广泛的应用,一些业界著名的开源组件也基于Netty的NIO框架构建。

netty使用

使用netty来写应用,应用的代码是非常复杂的。但是大部分的代码都属于模板代码。我们只需要复制过来,然后把我们的业务逻辑嵌入进去就可以了。

下面给出一个最简单的netty例子。

netty使用Sample

EchoServer.java

package com.mrbcy.bigdata.basic.netty.server;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;/** * • 配置服务器功能,如线程、端口 • 实现服务器处理程序,它包含业务逻辑,决定当有一个请求连接或接收数据时该做什么 *  * @author wilson * */public class EchoServer {    private final int port;    public EchoServer(int port) {        this.port = port;    }    public void start() throws Exception {        EventLoopGroup eventLoopGroup = null;        try {            //server端引导类            ServerBootstrap serverBootstrap = new ServerBootstrap();            //连接池处理数据            eventLoopGroup = new NioEventLoopGroup();            //装配bootstrap            serverBootstrap.group(eventLoopGroup)            .channel(NioServerSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel            .localAddress("localhost",port)//设置InetSocketAddress让服务器监听某个端口已等待客户端连接。            .childHandler(new ChannelInitializer<Channel>() {//设置childHandler执行所有的连接请求                @Override                protected void initChannel(Channel ch) throws Exception {                    ch.pipeline().addLast(new EchoServerHandler());//注册handler                }            });            // 最后绑定服务器等待直到绑定完成,调用sync()方法会阻塞直到服务器完成绑定,然后服务器等待通道关闭,因为使用sync(),所以关闭操作也会被阻塞。            ChannelFuture channelFuture = serverBootstrap.bind().sync();            System.out.println("开始监听,端口为:" + channelFuture.channel().localAddress());            channelFuture.channel().closeFuture().sync();        } finally {            eventLoopGroup.shutdownGracefully().sync();        }    }    public static void main(String[] args) throws Exception {        new EchoServer(20000).start();    }}

EchoServerHandler.java

package com.mrbcy.bigdata.basic.netty.server;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import java.util.Date;public class EchoServerHandler extends ChannelInboundHandlerAdapter {    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg)            throws Exception {        System.out.println("server 读取数据……");        //读取数据        ByteBuf buf = (ByteBuf) msg;        byte[] req = new byte[buf.readableBytes()];        buf.readBytes(req);        String body = new String(req, "UTF-8");        System.out.println("接收客户端数据:" + body);        //向客户端写数据        System.out.println("server向client发送数据");        String currentTime = new Date(System.currentTimeMillis()).toString();        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());//        ctx.writeAndFlush(resp);        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);    }    @Override    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {        System.out.println("server 读取数据完毕..");//        ctx.flush();//刷新后才将数据发出到SocketChannel    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)            throws Exception {        cause.printStackTrace();        ctx.close();    }}

EchoClient.java

package com.mrbcy.bigdata.basic.netty.client;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;import java.net.InetSocketAddress;/** * • 连接服务器 • 写数据到服务器 • 等待接受服务器返回相同的数据 • 关闭连接 *  * @author wilson * */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 nioEventLoopGroup = null;        try {            // 客户端引导类            Bootstrap bootstrap = new Bootstrap();            // EventLoopGroup可以理解为是一个线程池,这个线程池用来处理连接、接受数据、发送数据            nioEventLoopGroup = new NioEventLoopGroup();            bootstrap.group(nioEventLoopGroup)//多线程处理                    .channel(NioSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel                    .remoteAddress(new InetSocketAddress(host, port))//地址                    .handler(new ChannelInitializer<SocketChannel>() {//业务处理类                                @Override                                protected void initChannel(SocketChannel ch)                                        throws Exception {                                    ch.pipeline().addLast(new EchoClientHandler());//注册handler                                }                            });            // 链接服务器            ChannelFuture channelFuture = bootstrap.connect().sync();            channelFuture.channel().closeFuture().sync();        } finally {            nioEventLoopGroup.shutdownGracefully().sync();        }    }    public static void main(String[] args) throws Exception {        new EchoClient("localhost", 20000).start();    }}

EchoClientHandler.java

package com.mrbcy.bigdata.basic.netty.client;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {    // 客户端连接服务器后被调用    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println("客户端连接服务器,开始发送数据……");        byte[] req = "QUERY TIME ORDER".getBytes();//消息        ByteBuf firstMessage = Unpooled.buffer(req.length);//发送类        firstMessage.writeBytes(req);//发送        ctx.writeAndFlush(firstMessage);//flush    }    // • 从服务器接收到数据后调用    @Override    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)            throws Exception {        System.out.println("client 读取server数据..");        // 服务端返回消息后        ByteBuf buf = (ByteBuf) msg;        byte[] req = new byte[buf.readableBytes()];        buf.readBytes(req);        String body = new String(req, "UTF-8");        System.out.println("服务端数据为 :" + body);    }    // • 发生异常时被调用    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)            throws Exception {        System.out.println("client exceptionCaught..");        // 释放资源        ctx.close();    }}

netty中Handler的调用顺序问题

如果server中initChannel方法添加4个Handler,代码如下:

.childHandler(new ChannelInitializer<Channel>() {//设置childHandler执行所有的连接请求    @Override    protected void initChannel(Channel ch) throws Exception {        // 注册两个InboundHandler,执行顺序为注册顺序,所以应该是InboundHandler1 InboundHandler2        // 注册两个OutboundHandler,执行顺序为注册顺序的逆序,所以应该是OutboundHandler2 OutboundHandler1        ch.pipeline().addLast(new EchoInHandler1());        ch.pipeline().addLast(new EchoInHandler2());        ch.pipeline().addLast(new EchoOutHandler1());        ch.pipeline().addLast(new EchoOutHandler2());     }});

InHandler的执行顺序是按照添加顺序执行,OutHandler的执行顺序是按照添加顺序的逆序执行的。注意:Out不能放到所有In的前面,否则不会生效。

netty书籍推荐

  • netty 权威指南
  • netty in action
0 0