Netty入门例子(一): EchoServerApp和EchoClientApp

Netty是一个高性能的网络框架,遵循异步和事件通知的模型,隐藏了复杂的NIO和多线程构建,提供了一层简单易用的API

在分布式微服务盛行的年代,与其快速搭建服务,按照配置构建微服务,还不如先入门其通讯原理,从通讯底层的构建去了解服务注册与发现

Netty作为众多分布式应用的底层通讯应用,学习Netty将有助于我们学习分布式和微服务

以下是来自《Netty实战》的入门例子以及个人的一些备注见解,个人刚刚入门,可能有些地方有误,在后面的学习中如果发现前面的理解或者总结有误的话,会回来勘误,感谢各位的浏览

ChannelHandler

package com.wuweixin.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.CharsetUtil;


/**
 * ChannelHandler在我看来是一个对Channel的环绕处理吧
 * 这个是我的个人理解,可能不正确,毕竟我刚入门
 * 如果各位朋友如果觉得这里面有问题,感谢分享个人见解,谢谢!
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter{

    /**
     * ByteBuf乍一看有点像NIO里的ByteBuffer,其实它是netty对缓冲的实现,更加高效
     * Netty有一个特点就是对数据的快速处理转换,这可能得益于自己实现的Buf吧
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("server receiver:"+byteBuf.toString(CharsetUtil.UTF_8));
        SocketChannel channel = (SocketChannel) ctx.channel();
        ctx.write(byteBuf);
    }

    /**
     * 这里的 addListener有一定的设计,因为netty这些操作都是异步
     * netty设计了一个类似于future的channelFuture,用来获取异步操作得到的结果
     * ChannelFuture会去执行监听器,这或许是netty提倡的事件监听吧
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

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

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;


public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{


    /**
     * 通道激活时候产生的事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("I am coming", CharsetUtil.UTF_8));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("client received:"+byteBuf.toString(CharsetUtil.UTF_8));
    }

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

应用引导类

package com.wuweixin.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;

import java.net.InetSocketAddress;

public class EchoServerApp {

    private int port;

    public EchoServerApp(int port){
        this.port = port;
    }

    public void start() throws Exception{
        final EchoServerHandler echoServerHandler = new EchoServerHandler();
        EventLoopGroup group =  new NioEventLoopGroup();
        try{
            ServerBootstrap bootstrap =  new ServerBootstrap();
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(echoServerHandler);
                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();
            future.channel().closeFuture().sync();
        }catch (Exception e ){
            e.printStackTrace();
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception{
        new EchoServerApp(8080).start();
    }

}
    package com.wuweixin.netty;
    
    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;
    
    public class EchoClientApp {
    
        private String path;
        private int port;
    
        public EchoClientApp(String path,int port){
            this.path = path;
            this.port = port;
        }
    
        public void start() throws Exception{
            EventLoopGroup eventLoopGroup =  new NioEventLoopGroup();
            try {
                Bootstrap bootstrap =  new Bootstrap();
                bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                        .remoteAddress(new InetSocketAddress(path,port))
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                socketChannel.pipeline().addLast(new EchoClientHandler());
                            }
                        });
                ChannelFuture future = bootstrap.connect().sync();
                future.channel().closeFuture().sync();
            }catch (Exception e){
                e.printStackTrace();
                eventLoopGroup.shutdownGracefully().sync();
            }
        }
    
        public static void main(String[] args) throws Exception{
            new EchoClientApp("127.0.0.1",8080).start();
        }
    
    }
简单做了点注释,作为学习netty的笔记,谢谢浏览,如果发现其中有什么错误,感谢各位的指出,谢谢

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值