Netty的介绍与使用--第一天
Netty介绍
Netty 是一个利用 Java 的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的 API 的客户端/服务器框架。
Netty 是一个广泛使用的 Java 网络编程框架(Netty 在 2011 年获得了Duke’s Choice Award,见https://www.java.net/dukeschoice/2011)。它活跃和成长于用户社区,像大型公司 Facebook 和 Instagram 以及流行 开源项目如 Infinispan, HornetQ, Vert.x, Apache Cassandra 和 阿里的Dubbo框架等都利用其强大的对于网络抽象的核心代码
通道(Channel)
在介绍Netty前,我们先看看NIO的Channel。
1.Channel(通道)与我们在IO中使用的流有些类似,但是又有如下的区别:
A 通道可以同时进行读写,而流只能读或写
B 通道可以实现异步读取数据
C 通道可以从缓冲区读数据,也可以写到数据到缓冲
2.我们在平时开发的过程中,经常使用的Channel类有这些:FileChannel、DatagramChannel、ServerSocketChannel和SocketChannel(ServerSocketChannel与IO中的ServerSocket类似,SocketChannel与IO中的Socket类似)
3.在此我们简单的举个例子关于Channel的使用。
在平时FileChannel我们主要用来对本地文件进行IO操作,其常用的方法有:
(1)public int read(ByteBuffer dst):从通道读取数据到缓冲区中。
(2)public int write(ByteBuffer src):从缓冲区的数据写到通道中。
(3)public long transferTo(long position,long count,WriteableByteChannle target):把数据从当前通道复制到目标通道中。
代码例子:
1.通过Channel把数据写入到文件中
public class NIOFIleChannel01{
//功能:向txt文件中写入一些内容
public static void main(String[] args)throw Exception{
String s = "hello ,linjiazeng";
// 打开文件或创建文件
FileOutputStream fileOutputStream = new FileOutputStream("d:\\file.txt");
//获取一个通道
FileChannel channel = fileOutputStream.getChannel();
//创建一个缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
//数据写入缓冲区
buffer.put(s.getBytes());
//改变缓冲区状态:
buffer.flip();
channel.write(buffer);
fileOutputStream.close();
}
}
2.通过Channel把文件内容读取出来
public class NIOFileChannel02 {
//读取文件数据,并输出到控制台
public static void main(String[] args) throws Exception {
File file = new File("d:\\file.txt");
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel channel = fileInputStream.