Netty框架:
Netty是一個基於JAVA NIO類庫的異步通訊框架,它的架構特點是異步非阻塞,基於事件驅動,高性能,高可靠性和高可定製性。
Netty應用場景:
1.分佈式開源框架dubbo,Zookeeper,RocketMQ底層rpc通訊使用就是netty。
2.遊戲開發中,底層是用netty通訊。
爲啥子選擇netty:
NIO的類庫和api繁雜,使用麻煩。需要熟悉掌握Selector,ServerSocketChannel SocketChannel ByteBuffer等;
需要具備其他額外的技能做鋪墊,多線程編程,因爲NIO編程涉及到Reactor模式,必須對多線程和網絡編程非常熟悉,才能寫出高質量的NIO程序。
可靠性能力補齊,工作量和難度非常大,例如客戶端面臨斷鏈重連,網絡閃斷,半包讀寫,失敗緩存,網絡擁塞和異常碼流的處理等等,NIO編程的特點即使功能開發相對容易,但是可靠性能力補齊工作量和難度非常大。
解決JDK的bug 。
Netty服務器端:
package com.itmayiedu.day04;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
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;
/**
* Netty服務器端
*/
public class NettyDem01 {
public static void main(String[] args) {
test01();
}
public static void test01(){
//創建服務對象
ServerBootstrap serverBootstrap = new ServerBootstrap();
//創建兩個線程池 一個監聽端口號 一個監聽NIO
ExecutorService boos = Executors.newCachedThreadPool();
ExecutorService work = Executors.newCachedThreadPool();
//線程池放入到工程組中
serverBootstrap.setFactory(new NioServerSocketChannelFactory(boos,work));
//誰管道工程
serverBootstrap.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("serverHandler",new ServerHandler());
return pipeline;
}
});
//綁定端口號
serverBootstrap.bind(new InetSocketAddress(8990));
System.out.println("Netty服務端啓動");
while (true){
try{
Thread.sleep(1000);
System.out.println("每隔1秒打印一次");
}catch (Exception ex){
}
}
}
}
package com.itmayiedu.day04;
import org.jboss.netty.channel.*;
public class ServerHandler extends SimpleChannelHandler {
//接受客戶端數據
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
super.messageReceived(ctx, e);
System.out.println("================>>>>>>>>>+messageReceived");
System.out.println("================>>>>>>>>服務端的數據:"+e.getMessage());
}
//接受出現的異常
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
super.exceptionCaught(ctx, e);
}
//必須建立連接,關閉通道是纔會觸發
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
}
//通道別關閉的時候觸發
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelClosed(ctx, e);
}
}
Netty客戶端代碼:
package com.itmayiedu.day04;
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;
/**
* Netty 客戶端
*/
public class NettyClient {
public static void main(String[] args) {
ClientBootstrap clientBootstrap= new ClientBootstrap();
ExecutorService book = Executors.newCachedThreadPool();
ExecutorService wook = Executors.newCachedThreadPool();
clientBootstrap.setFactory(new NioClientSocketChannelFactory(book,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("clientHandler",new ClientHandler());
return pipeline;
}
});
//綁定端口號
ChannelFuture connect = clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 8990));
System.out.println("====================>>>>>>>>>>客戶端已經啓動。。");
Channel channel = connect.getChannel();
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("===============>>>>>>>>>>>>>>請輸入內容");
channel.write(scanner.next());
}
}
}
ClientHandler
package com.itmayiedu.day04;
import org.jboss.netty.channel.*;
public class ClientHandler extends SimpleChannelHandler {
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelClosed(ctx, e);
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
super.exceptionCaught(ctx, e);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
super.messageReceived(ctx, e);
System.out.println("=================>>>>>>>>:客戶端發送的數據:"+e.getMessage());
ctx.getChannel().write("你好啊");
}
}
`` `
io和NIO區別:
NIO面向緩衝區,非阻塞(是通過選擇器實現的)
IO面向流,是阻塞的。