学习——NIO原理概述及聊天示例

NIO编程

1. 概述

java.nio 全称 java non-blocking IO,是指 JDK 提供的新 API。从 JDK1.4 开始,Java 提供了一系列改进的输入/输出的新特性,被统称为 NIO(即 New IO)。新增了许多用于处理输入输出的类,这些类都被放在 java.nio 包及子包下,并且对原 java.io 包中的很多类进行改写,新增了满足 NIO 的功能。
NIO 和 BIO 有着相同的目的和作用,但是它们的实现方式完全不同,BIO 以流的方式处
理数据,而 NIO 以块的方式处理数据,块 I/O 的效率比流 I/O 高很多。另外,NIO 是非阻塞式的,这一点跟 BIO 也很不相同,使用它可以提供非阻塞式的高伸缩性网络。
NIO 主要有三大核心部分:Channel(通道),Buffer(缓冲区), Selector(选择器)。
传统的 BIO基于字节流和字符流进行操作,而 NIO 基于 Channel(通道)和 Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。通道与流的不同之处在于通道是双向的。而流只是在一个方向上移动(一个流必须是 InputStream 或者 OutputStream 的子类), 而 通道 可以用于读、写或者同时用于读写。因为它们是双向的,所以通道可以比流更好地反映底层操作系统的真实情况。
Selector(选择区)用于监听多个通道的事件(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道。

2. 文件IO

2.1.概述

缓冲区(Buffer):实际上是一个容器,是一个特殊的数组,缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况。Channel 提供从文件、网络读取数据的渠道,但是读取或写入的数据都必须经由 Buffer,如下图所示:
文件NIO
在 NIO 中,Buffer 是一个顶层父类,它是一个抽象类,常用的 Buffer 子类有:

  • ByteBuffer,存储字节数据到缓冲区
  • ShortBuffer,存储字符串数据到缓冲区
  • CharBuffer,存储字符数据到缓冲区
  • IntBuffer,存储整数数据到缓冲区
  • LongBuffer,存储长整型数据到缓冲区
  • DoubleBuffer,存储小数到缓冲区
  • FloatBuffer,存储小数到缓冲区
    对于 Java 中的基本数据类型,都有一个 Buffer 类型与之相对应,最常用的自然是
    ByteBuffer 类(二进制数据),该类的主要方法如下所示:
  • public abstract ByteBuffer put(byte[] b); 存储字节数据到缓冲区
  • public abstract byte[] get(); 从缓冲区获得字节数据
  • public final byte[] array(); 把缓冲区数据转换成字节数组
  • public static ByteBuffer allocate(int capacity); 设置缓冲区的初始容量
  • public static ByteBuffer wrap(byte[] array); 把一个现成的数组放到缓冲区中使用
  • public final Buffer flip(); 翻转缓冲区,重置位置到初始位置
    通道(Channel):类似于 BIO 中的 stream,例如 FileInputStream 对象,用来建立到目标(文件,网络套接字,硬件设备等)的一个连接,但是需要注意:BIO 中的 stream 是单向的,例如 FileInputStream 对象只能进行读取数据的操作,而 NIO 中的通道(Channel)是双向的,既可以用来进行读操作,也可以用来进行写操作。常用的 Channel 类有:FileChannel、DatagramChannel、ServerSocketChannel 和 SocketChannel。FileChannel 用于文件的数据读写,DatagramChannel 用于 UDP 的数据读写,ServerSocketChannel 和 SocketChannel 用于 TCP 的数据读写。
    这里我们先讲解 FileChannel 类,该类主要用来对本地文件进行 IO 操作,主要方法如下:
  • public int read(ByteBuffer dst) ,从通道读取数据并放到缓冲区中
  • public int write(ByteBuffer src) ,把缓冲区的数据写到通道中
  • public long transferFrom(ReadableByteChannel src, long position, long count),从目标通道中复制数据到当前通道
  • public long transferTo(long position, long count, WritableByteChannel target),把数据从当前通道复制给目标通道
2.2 示例
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO FileChannel Demo
 * 
 * @author Administrator
 *
 */
public class FileChannelDemo {

	/**
	 * NIO 中的通道是从输出流对象里通过 getChannel 方法获取到的,该通道是双向的,既可 以读,又可以写。在往通道里写数据之前,必须通过 put
	 * 方法把数据存到 ByteBuffer 中,然 后通过通道的 write 方法写数据。在 write 之前,需要调用 flip 方法翻转缓冲区,把内部重置
	 * 到初始位置,这样在接下来写数据时才能把所有数据写到通道里
	 * 
	 * @param content  准备写入的内容
	 * @param filePath 写入目标文件路径
	 * @throws IOException
	 */
	public void write(String content, String filePath) throws IOException {
		// 获取输出流
		FileOutputStream fos = new FileOutputStream(filePath);
		// 从输出流获取文件通道
		FileChannel channel = fos.getChannel();
		// 得到ByteBuffer 并设置容量
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		// 将内容放入
		buffer.put(content.getBytes());
		// 翻转
		buffer.flip();
		channel.write(buffer);
		fos.close();
	}

	/**
	 * 从输入流中获得一个通道,然后提供 ByteBuffer 缓冲区,该缓冲区的初始容量 和文件的大小一样,最后通过通道的 read
	 * 方法把数据读取出来并存储到了 ByteBuffer 中
	 * 
	 * @param filePath 读取文件路径
	 * @throws IOException
	 */
	public void read(String filePath) throws IOException {
		// 创建文件对象
		File file = new File(filePath);
		// 获取文件输入流
		FileInputStream fis = new FileInputStream(file);
		// 获取文件通道
		FileChannel channel = fis.getChannel();
		ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
		channel.read(buffer);
		System.out.println("读取到内容:" + new String(buffer.array()));
		fis.close();
	}

	/**
	 * BIO 文件复制功能
	 * 
	 * @param sourceFile 源文件路径
	 * @param targetFile 目标文件路径
	 */
	public void copyByBIO(String sourceFile, String targetFile) throws IOException {
		FileInputStream fis = new FileInputStream(sourceFile);
		FileOutputStream fos = new FileOutputStream(targetFile);
		byte[] b = new byte[1024];
		while (true) {
			int res = fis.read(b);
			if (res == -1) {
				break;
			}
			fos.write(b, 0, res);
		}
		fis.close();
		fos.close();
	}

	/**
	 * NIO 文件复制功能
	 * 
	 * @param sourceFile 源文件路径
	 * @param targetFile 目标文件路径
	 */
	public void copyByNIO(String sourceFile, String targetFile) throws IOException {
		FileInputStream fis = new FileInputStream(sourceFile);
		FileOutputStream fos = new FileOutputStream(targetFile);
		FileChannel sourceChannel = fis.getChannel();
		FileChannel targetChnnel = fos.getChannel();
		// 以下两种方式都可以
		// targetChnnel.transferFrom(sourceChannel, 0, sourceChannel.size());
		sourceChannel.transferTo(0, sourceChannel.size(), targetChnnel);
		sourceChannel.close();
		targetChnnel.close();
		fis.close();
		fos.close();
	}
}

3.网络 IO

3.1 概述

前面在进行文件 IO 时用到的 FileChannel 并不支持非阻塞操作,学习 NIO 主要就是进行
网络 IO,Java NIO 中的网络通道是非阻塞 IO 的实现,基于事件驱动,非常适用于服务器需要维持大量连接,但是数据交换量不大的情况,例如一些即时通信的服务等等…
在 Java 中编写 Socket 服务器,通常有以下几种模式:

  • 一个客户端连接用一个线程,优点:程序编写简单;缺点:如果连接非常多,分配的线
    程也会非常多,服务器可能会因为资源耗尽而崩溃。
  • 把每一个客户端连接交给一个拥有固定数量线程的连接池,优点:程序编写相对简单,
    可以处理大量的连接。缺点:线程的开销非常大,连接如果非常多,排队现象会比较严
    重。
  • 使用 Java 的 NIO,用非阻塞的 IO 方式处理。这种模式可以用一个线程,处理大量的客户端连接。
    [外链图片转存失败(img-RUFGZcu4-1568271699363)(http://img3.imgtn.bdimg.com/it/u=2534199603,674087730&fm=26&gp=0.jpg)]
    Selector(选择器) 能够检测多个注册的通道上是否有事件发生,如果有事件发生,便获取事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管理多个通道,也就是管理多个连接。这样使得只有在连接真正有读写事件发生时,才会调用函数来进行读写,就大大地减少了系统开销,并且不必为每个连接都创建一个线程,不用去维护多个线程,并且避免了多线程之间的上下文切换导致的开销。
    该类的常用方法如下所示:
  • public static Selector open(),得到一个选择器对象
  • public int select(long timeout),监控所有注册的通道,当其中有 IO 操作可以进行时,将对应的 SelectionKey 加入到内部集合中并返回,参数用来设置超时时间
  • public Set selectedKeys(),从内部集合中得到所有的 SelectionKey
    SelectionKey 代表了 Selector 和网络通道的注册关系,一共四种:
  • int OP_ACCEPT:有新的网络连接可以 accept,值为 16
  • int OP_CONNECT:代表连接已经建立,值为 8
  • int OP_READ 和 int OP_WRITE:代表了读、写操作,值为 1 和 4
    该类的常用方法如下所示:
  • public abstract Selector selector(),得到与之关联的 Selector 对象
  • public abstract SelectableChannel channel(),得到与之关联的通道
  • public final Object attachment(),得到与之关联的共享数据
  • public abstract SelectionKey interestOps(int ops),设置或改变监听事件
  • public final boolean isAcceptable(),是否可以 accept
  • public final boolean isReadable(),是否可以读
  • public final boolean isWritable(),是否可以写
    ServerSocketChannel 用来在服务器端监听新的客户端 Socket 连接,常用方法如下所示:
  • public static ServerSocketChannel open(),得到一个 ServerSocketChannel 通道
  • public final ServerSocketChannel bind(SocketAddress local),设置服务器端端口号
  • public final SelectableChannel configureBlocking(boolean block),设置阻塞或非阻塞模式,取值 false 表示采用非阻塞模式
  • public SocketChannel accept(),接受一个连接,返回代表这个连接的通道对象
  • public final SelectionKey register(Selector sel, int ops),注册一个选择器并设置监听事件
    SocketChannel 网络 IO 通道,具体负责进行读写操作。NIO 总是把缓冲区的数据写入通道,或者把通道里的数据读到缓冲区。常用方法如下所示:
  • public static SocketChannel open(),得到一个 SocketChannel 通道
  • public final SelectableChannel configureBlocking(boolean block),设置阻塞或非阻塞模式,取值 false 表示采用非阻塞模式
  • public boolean connect(SocketAddress remote),连接服务器
  • public boolean finishConnect(),如果上面的方法连接失败,接下来就要通过该方法完成连接操作
  • public int write(ByteBuffer src),往通道里写数据
  • public int read(ByteBuffer dst),从通道里读数据
  • public final SelectionKey register(Selector sel, int ops, Object att),注册一个选择器并设置监听事件,最后一个参数可以设置共享数据
  • public final void close(),关闭通道
3.2. 示例

示例一 服务端客户端通信

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * NIO 服务端
 * 
 * @author Administrator
 *
 */
public class NIOServer {
	public static void main(String[] args) throws Exception {
		// 获取ServerSocketChannel
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		// 获取Selector对象
		Selector selector = Selector.open();
		// 绑定服务端口
		serverSocketChannel.bind(new InetSocketAddress(666));
		// 设置服务端为非阻塞模式
		serverSocketChannel.configureBlocking(false);
		// 将ServerSocketChannel 注册到Selector
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		while (true) {
			// 监听客户端
			if (selector.select(2000) == 0) {
				System.out.println("NIOServer:暂时没有客户端操。。。");
			}
			// 得到SelectionKey,判断通道事件
			Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
			while (selectionKeys.hasNext()) {
				SelectionKey selectionKey = selectionKeys.next();
				if (selectionKey.isAcceptable()) {
					// 连接事件
					System.out.println("NIOServer:Client Accept.");
					SocketChannel socketChannel = serverSocketChannel.accept();
					// 设置非阻塞模式并注册到Selector
					socketChannel.configureBlocking(false);
					socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
				}
				if (selectionKey.isReadable()) {
					// 读取数据事件
					SocketChannel channel = (SocketChannel) selectionKey.channel();
					ByteBuffer attachment = (ByteBuffer) selectionKey.attachment();
					channel.read(attachment);
					System.out.println("NIOClient:" + new String(attachment.array()));
				}
				// 手动从集合中移除当前 key,防止重复处理
				selectionKeys.remove();
			}
		}
	}
}
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * NIO 客户端
 * 
 * @author Administrator
 *
 */
public class NIOClient {
	public static void main(String[] args) throws IOException {

		// 获取 SocketChannel
		SocketChannel socketChannel = SocketChannel.open();
		// 设置非阻塞模式
		socketChannel.configureBlocking(false);
		// 连接服务端
		InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 666);
		if (!socketChannel.connect(socketAddress)) {
			// 连接失败 则使用下面的操作完成连接
			while (!socketChannel.finishConnect()) {
				System.out.println("NIOClient:尝试连接服务端。。。");
			}
		}
		// 准备发送数据
		ByteBuffer buffer = ByteBuffer.wrap("Hello NIOServer".getBytes());
		// 发送数据
		socketChannel.write(buffer);
		System.in.read();
	}
}

示例二 群聊

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class ChatServer {
	private Selector selector;
	private ServerSocketChannel serverSocketChannel;
	private static final int PORT = 666; // 服务端口

	public ChatServer() {
		try {
			// 得到选择器
			selector = Selector.open();
			// 打开监听通道
			serverSocketChannel = ServerSocketChannel.open();
			// 绑定端口
			serverSocketChannel.bind(new InetSocketAddress(PORT));
			// 设置为非阻塞模式
			serverSocketChannel.configureBlocking(false);
			// 将选择器绑定到监听通道并监听 accept 事件
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
			System.out.println("ChatServer 已就绪.......");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void start() {
		try {
			while (true) {
				// 监听客户端
				int select = selector.select();
				if (select == 0) {
					System.out.println("ChatServer:暂时没有用户操作。。。");
				}
				// 得到SelectionKey,判断通道事件
				Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
				while (selectionKeys.hasNext()) {
					SelectionKey selectionKey = selectionKeys.next();
					if (selectionKey.isAcceptable()) {
						// 连接事件
						System.out.println("NIOServer:Client Accept.");
						SocketChannel socketChannel = serverSocketChannel.accept();
						// 设置非阻塞模式并注册到Selector 监听 read
						socketChannel.configureBlocking(false);
						socketChannel.register(selector, SelectionKey.OP_READ);
						System.out.println(socketChannel.getRemoteAddress().toString().substring(1) + "上线了...");
						// 将此对应的 channel 设置为 accept,接着准备接受其他客户端请求
						selectionKey.interestOps(SelectionKey.OP_ACCEPT);
					}
					if (selectionKey.isReadable()) {
						// 读取数据事件
						readMsg(selectionKey);
					}
					// 手动从集合中移除当前 key,防止重复处理
					selectionKeys.remove();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取 SelectionKey对应通道发送的数据
	 * 
	 * @param key SelectionKey
	 */
	private void readMsg(SelectionKey key) {
		SocketChannel channel = null;
		try {
			// 得到关联的通道
			channel = (SocketChannel) key.channel();
			// 设置 buffer 缓冲区
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			// 从通道中读取数据并存储到缓冲区中
			int count = channel.read(buffer);
			// 如果读取到了数据
			if (count > 0) {
				// 把缓冲区数据转换为字符串
				String msg = new String(buffer.array());
				// 将关联的 channel 设置为 read,继续准备接受数据
				key.interestOps(SelectionKey.OP_READ);
				broadCast(channel, msg); // 向所有客户端广播数据
			}
			buffer.clear();
		} catch (IOException e) {
			try {
				// 当客户端关闭 channel 时,进行异常如理
				System.out.println(channel.getRemoteAddress().toString().substring(1) + "下线了...");
				key.cancel(); // 取消注册
				channel.close(); // 关闭通道
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	public void broadCast(SocketChannel except, String msg) throws IOException {
		// 广播数据到所有的 SocketChannel 中
		for (SelectionKey key : selector.keys()) {
			Channel targetchannel = key.channel();
			// 排除自身
			if (targetchannel instanceof SocketChannel && targetchannel != except) {
				SocketChannel dest = (SocketChannel) targetchannel;
				// 把数据存储到缓冲区中
				ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
				// 往通道中写数据
				dest.write(buffer);
			}
		}
	}

	public static void main(String[] args) {
		ChatServer server = new ChatServer();
		server.start();
	}
}
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class ChatClient {
	private final String HOST = "127.0.0.1"; // 服务器地址
	private int PORT = 666; // 服务器端口
	private Selector selector;
	private SocketChannel socketChannel;
	private String userName;

	public ChatClient() throws IOException {
		// 得到选择器
		selector = Selector.open();
		// 连接远程服务器
		socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
		// 设置非阻塞
		socketChannel.configureBlocking(false);
		// 注册选择器并设置为 read
		socketChannel.register(selector, SelectionKey.OP_READ);
		// 得到客户端 IP 地址和端口信息,作为聊天用户名使用
		userName = socketChannel.getLocalAddress().toString().substring(1);
		System.out.println("---------------Client(" + userName + ") 就绪------");
	}

	/**
	 * 向服务器端发送数据
	 * 
	 * @param msg 发送的消息
	 * @throws Exception
	 */
	public void sendMsg(String message) throws Exception {
		// 如果控制台输入 bye 就关闭通道,结束聊天
		if (message.equalsIgnoreCase("bye")) {
			socketChannel.close();
			socketChannel = null;
			return;
		}
		message = userName + ": " + message;
		try {
			// 往通道中写数据
			socketChannel.write(ByteBuffer.wrap(message.getBytes()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从服务器端接收数据
	 */
	public void receiveMsg() {
		try {
			int readyChannels = selector.select();
			if (readyChannels > 0) { // 有可用通道
				Set<?> selectedKeys = selector.selectedKeys();
				Iterator<?> keyIterator = selectedKeys.iterator();
				while (keyIterator.hasNext()) {
					SelectionKey sk = (SelectionKey) keyIterator.next();
					if (sk.isReadable()) {
						// 得到关联的通道
						SocketChannel sc = (SocketChannel) sk.channel();
						// 得到一个缓冲区
						ByteBuffer buff = ByteBuffer.allocate(1024);
						// 读取数据并存储到缓冲区
						sc.read(buff);
						// 把缓冲区数据转换成字符串
						String msg = new String(buff.array());
						System.out.println(msg.trim());
					}
					// 删除当前 SelectionKey,防止重复处理
					keyIterator.remove();
				}
			} else {
				System.out.println("nobady...");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		// 创建一个聊天客户端对象
		ChatClient chatClient = new ChatClient();
		new Thread() { // 单独开一个线程不断的接收服务器端广播的数据
			public void run() {
				while (true) {
					chatClient.receiveMsg();
					try { // 间隔 1秒
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		Scanner scanner = new Scanner(System.in);
		// 在控制台输入数据并发送到服务器端
		while (scanner.hasNextLine()) {
			String msg = scanner.nextLine();
			chatClient.sendMsg(msg);
		}
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值