netty学习

netty简介:

Netty是由JBOSS提供的一个开源的java网络编程框架,作者是Trustin Lee,同时也是事件驱动服务通信框架,那什么是事件驱动服务通信框架?我们以后再说。这个框架是基于java的nio模型进行高度封装的框架。再次说明,netty是网络编程框架。网络通信,server/client 模式通信,长连接都可以用它。

为什么要学netty?

1很多框架底层通信都使用netty,如果需要研究框架就需要学习netty。
2现在大多数框架都是分布式开发,分布式意味着需要网络通信,java的网络通信就是socket编程,随着java的版本迭代,socket编程从bio,到nio再到aio。netty就是基于繁琐的nio api来开发的。假如你要开发一个分布式框架,那么网络通信是必须要考虑的。

3可以学到reactor模型,disrupter框架等等,为以后学写中间件框架打好基础。

netty入门:

你只需要把下面代码粘贴到ide中查看效果,那这样就可以知道netty怎么用了。

1如果是maven工程,那么直接在pom.xml 中引入依赖

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

2server端代码

public class NettyServer {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        NioEventLoopGroup boos = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap
                .group(boos, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println(msg);
                            }
                        });
                    }
                })
                .bind(8000);
    }
}

client端代码

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });

        Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();

        while (true) {
            channel.writeAndFlush(new Date() + ": hello world!");
            Thread.sleep(2000);
        }
    }
}

如果你已经完成上述步骤,那么先运行server端代码,然后在运行client端代码,看运行的效果。如果在控制台输出时间+hello world!,那么netty就运行起来了。

下一篇文章介绍上面的代码是什么意思。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值