Netty
是一款基于NIO(Nonblocking I/O,非阻塞IO)开发的网络通信框架,提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。对比于BIO(Blocking I/O,阻塞IO),他的并发性能得到了很大提高。
提供了对TCP、UDP和文件传输的支持,作为一个异步NIO框架,Netty的所有IO操作都是异步非阻塞的,通过Future-Listener机制,用户可以方便的主动获取或者通过通知机制获得IO操作结果。
并发高
传输快
封装好
Netty部分构件
1. Channel
在Netty里,Channel是通讯的载体,而ChannelHandler负责Channel中的逻辑处理。它是Netty网络通信的主体,由它负责同对端进行网络通信、注册和数据操作等功能。
状态主要包括:打开、关闭、连接
主要的IO操作,读(read)、写(write)、连接(connect)、绑定(bind)。
所有的IO操作都是异步的,调用诸如read,write方法后,并不保证IO操作完成,但会返回一个凭证,在IO操作成功,取消或失败后会记录在该凭证中。
2. ChannelPipeline
可以理解为ChannelHandler的容器:一个Channel包含一个ChannelPipeline,所有ChannelHandler都会注册到ChannelPipeline中,并按顺序组织起来。channel事件消息在ChannelPipeline中流动和传播,相应的事件能够被ChannelHandler拦截处理、传递、忽略或者终止。
Netty的ChannelPipeline包含两条线路:Upstream和Downstream。Upstream对应上行,接收到的消息、被动的状态改变,都属于Upstream。Downstream则对应下行,发送的消息、主动的状态改变,都属于Downstream。
3. ChannelHandler
ChannelHandler负责I/O事件或者I/O操作进行拦截和处理,用户可以通过ChannelHandlerAdapter来选择性的实现自己感兴趣的事件拦截和处理。由于Channel只负责实际的I/O操作,因此数据的编解码和实际处理都需要通过ChannelHandler进行处理。
Netty实现Server和Client通信
项目结构,两个protocol目录下内容相同,定义了通信时的编码解码,传输类。
1. 添加依赖,netty-all(必须),fastjson(用于传输对象的序列化,可选择其它方法)
2. Server端
/*
* @author uv
* @date 2018/10/12 18:25
* 服务端
*/
import com.uv.protocol.RpcDecoder;
import com.uv.protocol.RpcEncoder;
import com.uv.protocol.RpcRequest;
import com.uv.protocol.RpcResponse;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyServer {
public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); //bossGroup就是parentGroup,是负责处理TCP/IP连接的
EventLoopGroup workerGroup = new NioEventLoopGroup(); //workerGroup就是childGroup,是负责处理Channel(通道)的I/O事件
ServerBootstrap sb = new ServerBootstrap();
sb.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128) //初始化服务端可连接队列,指定了队列的大小128
.childOption(ChannelOption.SO_KEEPALIVE, true) //保持长连接
.childHandler(new ChannelInitializer
@Override
protected void initChannel(SocketChannel sh) throws Exception {
sh.pipeline()
.addLast(new RpcDecoder(RpcRequest.class)) //解码request
.addLast(new RpcEncoder(RpcResponse.class)) //编码response
.addLast(new ServerHandler()); //使用ServerHandler类来处理接收到的消息
}
});
//绑定监听端口,调用sync同步阻塞方法等待绑定操作完
ChannelFuture future = sb.bind(port).sync();
if (future.isSuccess()) {
System.out.println("服务端启动成功");
} else {
System.out.println("服务端启动失败");
future.cause().printStackTrace();
bossGroup.shutdownGracefully(); //关闭线程组
workerGroup.shutdownGracefully();
}
//成功绑定到端口之后,给channel增加一个 管道关闭的监听器并同步阻塞,直到channel关闭,线程才会往下执行,结束进程。
future.channel().closeFuture().sync();
}
}
3. Server的消息处理类Handler,继承ChannelInboundHandlerAdapter
import com.uv.protocol.RpcRequest;
import com.uv.protocol.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.UUID;
public class ServerHandler extends ChannelInboundHandlerAdapter{
//接受client发送的消息
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
RpcRequest request = (RpcRequest) msg;
System.out.println("接收到客户端信息:" + request.toString());
//返回的数据结构
RpcResponse response = new RpcResponse();
response.setId(UUID.randomUUID().toString());
response.setData("server响应结果");
response.setStatus(1);
ctx.writeAndFlush(response);
}
//通知处理器最后的channelRead()是当前批处理中的最后一条消息时调用
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("服务端接收数据完毕..");
ctx.flush();
}
//读操作时捕获到异常时调用
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
//客户端去和服务端连接成功时触发
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// ctx.writeAndFlush("hello client");
}
}
4. Client端
/*
* @author uv
* @date 2018/10/12 20:54
*
*/
import com.uv.protocol.RpcDecoder;
import com.uv.protocol.RpcEncoder;
import com.uv.protocol.RpcRequest;
import com.uv.protocol.RpcResponse;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class NettyClient {
private final String host;
private final int port;
private Channel channel;
//连接服务端的端口号地址和端口号
public NettyClient(String host, int port) {
this.host = host;
this.port = port;
}
public void start() throws Exception {
final EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
.handler(new ChannelInitializer
@Override
public void initChannel(SocketChannel ch) throws Exception {
System.out.println("正在连接中...");
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new RpcEncoder(RpcRequest.class)); //编码request
pipeline.addLast(new RpcDecoder(RpcResponse.class)); //解码response
pipeline.addLast(new ClientHandler()); //客户端处理类
}
});
//发起异步连接请求,绑定连接端口和host信息
final ChannelFuture future = b.connect(host, port).sync();
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture arg0) throws Exception {
if (future.isSuccess()) {
System.out.println("连接服务器成功");
} else {
System.out.println("连接服务器失败");
future.cause().printStackTrace();
group.shutdownGracefully(); //关闭线程组
}
}
});
this.channel = future.channel();
}
public Channel getChannel() {
return channel;
}
}
5. Client的消息处理类Handler,继承SimpleChannelInboundHandler
/*
* @author uv
* @date 2018/10/12 20:56
* client消息处理类
*/
import com.uv.protocol.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class ClientHandler extends SimpleChannelInboundHandler
//处理服务端返回的数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {
System.out.println("接受到server响应数据: " + response.toString());
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
6. 编码和解码
解码器
/*
* @author uv
* @date 2018/10/13 18:09
* 解码器(将接收的数据转换成实体类)
*/
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
public class RpcDecoder extends ByteToMessageDecoder {
//目标对象类型进行解码
private Class> target;
public RpcDecoder(Class target) {
this.target = target;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List
/*
* @author uv
* @date 2018/10/13 18:09
* 编码器(将实体类转换成可传输的数据)
*/
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class RpcEncoder extends MessageToByteEncoder {
//目标对象类型进行编码
private Class> target;
public RpcEncoder(Class target) {
this.target = target;
}
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
if (target.isInstance(msg)) {
byte[] data = JSON.toJSONBytes(msg); //使用fastJson将对象转换为byte
out.writeInt(data.length); //先将消息长度写入,也就是消息头
out.writeBytes(data); //消息体中包含我们要发送的数据
}
}
}
7. 传输实体类(RpcRequest、RpcResponse)
/*
* @author uv
* @date 2018/10/13 18:10
* 传输请求对象
*/
public class RpcRequest {
private String id;
private Object data;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "RpcRequest{" + "id='" + id + '\'' + ", data=" + data + '}';
}
}
/*
* @author uv
* @date 2018/10/13 18:10
* 传输响应对象
*/
public class RpcResponse {
private String id;
private Object data;
// 0=success -1=fail
private int status;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public String toString() {
return "RpcResponse{" + "id='" + id + '\'' + ", data=" + data + ", status=" + status + '}';
}
}
8. Server和Client启动类
Server启动
import com.uv.server.NettyServer;
/**
*
*/
public class Main {
public static void main(String[] args) throws Exception {
//启动server服务
new NettyServer().bind(8080);
}
}
Client启动
import com.uv.client.NettyClient;
import com.uv.protocol.RpcRequest;
import io.netty.channel.Channel;
import java.util.UUID;
/**
*
*/
public class Main {
public static void main(String[] args) throws Exception {
NettyClient client = new NettyClient("127.0.0.1", 8080);
//启动client服务
client.start();
Channel channel = client.getChannel();
//消息体
RpcRequest request = new RpcRequest();
request.setId(UUID.randomUUID().toString());
request.setData("client.message");
//channel对象可保存在map中,供其它地方发送消息
channel.writeAndFlush(request);
}
}
8. 依次启动Server和Client,测试结果
Server端输出
Client端输出
github源码地址: https://github.com/UVliuwei/netty