优势
1.API使用简单,开发门槛低
2.功能强大,预置了多种编码功能,支持多种主流协议;
3.定制能力强,可以通过channelHandler对通信框架进行灵活地扩展;
4.性能高,通过与其他业界主流的NIO框架对比,netty的综合性能最优;
5.成熟、稳定,netty修复了已发现的所有jdk nio bug,业务开发人员不需要再为nio的bug而烦恼;
核心组件
Bootstrap、EvenLoop(Group)、Channel
Bootstrap:启动类,注方法类
EvenLoop:事件循环, 可以理解为一个线程
Channel:类似于Socket
事件和 ChannelHandler、ChannelPipeline
事件:把网络上法生的事情,和要做的事情包装成了事件
ChannelHandler:负责处理事件
ChannelPipeline:负责把ChannelHandler组织在一起(责任链模式)
ChannelFuture
出站操作,类似于future异步
代码
核心就是引擎这块
,客户端,服务端万变不离其宗
客户端(固定的)
/**
* 作者:yuyang
* 类说明:基于Netty的客户端
*/
public class EchoClient {
private final int port;
private final String host;
public EchoClient(int port, String host) {
this.port = port;
this.host = host;
}
public void start() throws InterruptedException {
/*线程组*/
EventLoopGroup group = new NioEventLoopGroup();
try {
/*客户端启动必备*/
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)/*指定使用NIO的通信模式*/
.remoteAddress(new InetSocketAddress(host,port))/*指定服务器的IP地址和端口*/
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
ChannelFuture f = b.connect().sync();/*异步连接到服务器,sync()会阻塞到完成*/
f.channel().closeFuture().sync();/*阻塞当前线程,直到客户端的Channel被关闭*/
} finally {
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws InterruptedException {
new EchoClient(9999,"127.0.0.1").start();
}
}
客户端引擎
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
/*读取到网络数据后进行业务处理*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("client Accept"+msg.toString(CharsetUtil.UTF_8));
ctx.close();
}
/*channel活跃后,做业务处理*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.copiedBuffer(
"Hello,Netty",CharsetUtil.UTF_8));
}
}
服务端(固定的)
/**
* 作者:yuyang
* 类说明:基于Netty的服务器
*/
public class EchoServer {
private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
private final int port;
public EchoServer(int port) {
this.port = port;
}
public static void main(String[] args) throws InterruptedException {
int port = 9999;
EchoServer echoServer = new EchoServer(port);
LOG.info("服务器即将启动");
echoServer.start();
LOG.info("服务器关闭");
}
public void start() throws InterruptedException {
final EchoServerHandler serverHandler = new EchoServerHandler();
/*线程组*/
EventLoopGroup group = new NioEventLoopGroup();
try {
/*服务端启动必备*/
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)/*指定使用NIO的通信模式*/
.localAddress(new InetSocketAddress(port))/*指定监听端口*/
//.childOption()
//.handler();
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(serverHandler);
}
});
ChannelFuture f = b.bind().sync();/*异步绑定到服务器,sync()会阻塞到完成*/
f.channel().closeFuture().sync();/*阻塞当前线程,直到服务器的ServerChannel被关闭*/
} finally {
group.shutdownGracefully().sync();
}
}
}
服务端引擎
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf)msg;
System.out.println("Server accept: "+in.toString(CharsetUtil.UTF_8));
ctx.writeAndFlush(in);
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}