一、背景
最近在看netty相关的源码,就想整理一下,加深一下印象。
Netty 是一个 网络编程框架,对Java socket通信编码做了很多的抽象封装,开发人员使用起来非常简单。
二、netty的简单应用
服务端源码
public class DemoServer {
public static void main(String[] args) throws InterruptedException {
//创建 boss线程,用来监听客户端的链接,一般线程数为1,
EventLoopGroup bossLoopGroup = new NioEventLoopGroup(1);
//创建工作线程,bossLoopGroup监听到链接后,会移交给工作线程来进行后续操作
EventLoopGroup workLoopGroup = new NioEventLoopGroup(4);
//服务端启动类,通过这个可以设置一系列的参数
ServerBootstrap serverBootstrap = new ServerBootstrap();
//设置主线程组,和工作线程组。
serverBootstrap.group(bossLoopGroup,workLoopGroup);
//指定服务端的channel,这是netty自己定义的channel,里面有一个变量保存JDK的ServerSocketChannel。
//netty底层的网络通信还是基于JDK相关的socket,channel
serverBootstrap.channel(NioServerSocketChannel.class);
//boss线程的处理类,当有新的客户端连接过来的时候可以通过这个handler预处理
serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
//work线程的处理类,当boss线程到新的客户端连接之后,会移交到work线程工作,具体要做什么就是由Handler实现的
//一般来说,都是定义 初始化的Handler(继承ChannelInitializer),通过实现ChannelInitializer.initChannel(SocketChannel ch)
//ChannelPipeline p = ch.pipeline(); p.addLast()方法来添加不同的Handler
//每个新的客户端连接过来之后,都会被这些Handler处理
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new StringDecoder(),new NettyServerHandler()); //将自己编写的客户端业务逻辑处理类加入到pipeline链中
}
});
//绑定端口启动服务端
Channel ch = serverBootstrap.bind(9090).sync().channel();
//等待服务端关闭socket
ch.closeFuture().sync();
// 关闭线程组
bossLoopGroup.shutdownGracefully();
workLoopGroup.shutdownGracefully();
}
}
客户端源码
public class DemoClient {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup eventExecutors = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventExecutors)
.channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(
new LengthFieldPrepender(4,false),
new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4),new StringDecoder(),
new NettyClientHandler()); //将自己编写的客户端业务逻辑处理类加入到pipeline链中
}
});
//设置服务端的ip和端口
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",9090).sync();
//关闭连接
channelFuture.channel().close().sync();
}
}
三、总结
从上面可以知道,netty是做了很多封装,对于开发人员来说,只要将自己的业务处理逻辑定义成Handler,加入到pipeline中就可以了。而且netty自己也定义了很多Handler,提供开发使用,比如 将btye 转成 String 处理类(StringDecoder),http请求相关的处理类(HttpResponseEncoder)等等,通过netty定义的处理类也可以自己实现HTTP,HTTPS的网络通信。