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就运行起来了。
下一篇文章介绍上面的代码是什么意思。