一、什么是netty
Netty是一个NIO客户端服务器框架,可以快速轻松地开发协议服务器和客户端等网络应用程序。它极大地简化并简化了TCP和UDP套接字服务器等网络编程。
“快速简便”并不意味着最终的应用程序会受到可维护性或性能问题的影响。Netty经过精心设计,具有丰富的协议,如FTP,SMTP,HTTP以及各种二进制和基于文本的传统协议。因此,Netty成功地找到了一种在不妥协的情况下实现易于开发,性能,稳定性和灵活性的方法。
二、特点
- 异步非阻塞(应用程序直接可以获取已经准备好的数据,无需等待.IO为同步阻塞形式,NIO为同步非阻塞形式。NIO没有实现异步,在JDK1.7之后,升级了NIO库包,支持异步费阻塞通讯模型NIO2.0(AIO))
- 基于事件驱动(比如:比如你定了个闹钟叫你早上6点起床,闹钟到6点准时响起,这就是一个事件,当你被闹钟吵醒,接下来你要做什么事,就是这个事件驱动的回调。这个回调的处理是你一开始就安排好的,只是说要等到某一个事件产生,你才会去做这件事。)
- 高性能、高可靠性和高可定制性。
三、应用场景
- 分布式开源框架中dubbo、Zookeeper,RocketMQ底层rpc通讯使用就是netty。
- 游戏开发中,底层使用netty通讯。
四、仓库地址
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.36.Final</version>
</dependency>
五、完成第一个NettyDemo
package netty;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @ClassName NettyServer
* @Description TODO
* @Author mc
* @Date 2019/7/29 15:47
* @Version 1.0
**/
public class NettyServer {
public static void main(String[] args) {
// 创建服务类对象
ServerBootstrap serverBootstrap = new ServerBootstrap();
//创建两个线程池 分别为监听监听端口 ,nio监听
ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService wook = Executors.newCachedThreadPool();
// 设置工程 并把两个线程池加入中
serverBootstrap.setFactory(new NioServerSocketChannelFactory(boss, wook));
// 设置管道工厂
serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
//将数据转换为string类型.
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("serverhanlder", new ServerHanlder());
return pipeline;
}
});
//绑定端口号
serverBootstrap.bind(new InetSocketAddress(8080));
System.out.println("netty server启动....");
}
}
服务端监听事件
import org.jboss.netty.channel.*;
/**
* 事件监听
*/
class ServerHanlder extends SimpleChannelHandler {
/**
* 通道呗关闭时触发
*
* @param ctx
* @param e
* @throws Exception
*/
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelClosed(ctx, e);
System.out.println("channelClosed");
}
//必须建立连接,关闭通道时才会被触发
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
System.out.println("exceptionCaught" + e.getState());
}
//接受出现的异常
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
super.exceptionCaught(ctx, e);
System.out.println("exceptionCaught" + ctx.getAttachment());
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
super.messageReceived(ctx, e);
System.out.println("exceptionCaught");
System.out.println("客户端发来信息:" + e.getMessage());
ctx.getChannel().write("来了老弟!"); //皮一下很开森
}
}
客户端代码:
package netty;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @ClassName NettyClinet
* @Description TODO
* @Author mc
* @Date 2019/7/29 16:06
* @Version 1.0
**/
public class NettyClinet {
public static void main(String[] args) {
// 创建服务类对象
ClientBootstrap clientBootstrap = new ClientBootstrap();
// 线程池
ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService wook = Executors.newCachedThreadPool();
// 设置工程 并把两个线程池加入中
clientBootstrap.setFactory(new NioClientSocketChannelFactory(boss, wook));
// 设置管道工厂
clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("clientHanlder", new ClientHanlder());
return pipeline;
}
});
//绑定端口号
ChannelFuture connect = clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
System.out.println("客户端已经启动。。。。。");
Channel channel = connect.getChannel();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请输入内容:");
channel.write(scanner.next());
}
}
}
监听事件和服务端一样
import org.jboss.netty.channel.*;
/**
* 事件监听
*/
class ClientHanlder extends SimpleChannelHandler {
//通道呗关闭时触发
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelClosed(ctx, e);
System.out.println("channelClosed");
}
//必须建立连接,关闭通道时才会被触发
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
System.out.println("exceptionCaught" + e.getState());
}
//接受出现的异常
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
super.exceptionCaught(ctx, e);
System.out.println("exceptionCaught" + ctx.getAttachment());
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
super.messageReceived(ctx, e);
System.out.println("exceptionCaught");
System.out.println("服务器端发来信息:" + e.getMessage());
}
}
服务端信息:
客户端信息: