经过查看资料,自我感觉 NIO 和 我们学习Java时候 的 Socket 通信相似,所以在查看有关 NIO 的案例进行记录:
IO是同步阻塞IO操作,当线程在处理任务时,另一方会阻塞着等待该线程的执行完毕,为了提高效率,,JDK1.4后,引入NIO来提升数据的通讯性能
NIO中采用Reactor设计模式,注册的汇集点为Selector,NIO有三个主要组成部分:Channel(通道)、Buffer(缓冲区)、Selector(选择器)
NIO采用了轮询的方式来观察事件是否执行完毕,如:
A让B打印某个文件,BIO会一直等待着B返回,期间自己不做其他事情,而NIO则会不断的询问B是否完成,未完成则处理自己的时,直至B完成
NIO 简单案例
NioServer 端:
进行创建通讯管道,并且监控是否又客户端进行连接:有的话就进行创建一个线程进行处理
package com.example.nio;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NIOServer {
public static void main(String[] args) throws Exception{
// 为了性能问题及响应时间,设置固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
// NIO基于Channel控制,所以有Selector管理所有的Channel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 设置为非阻塞模式
serverSocketChannel.configureBlocking(false);
// 设置监听端口
serverSocketChannel.bind(new InetSocketAddress(HostInfo.PORT));
// 设置Selector管理所有Channel
Selector selector = Selector.open();
// 注册并设置连接时处理
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("服务启动成功,监听端口为:" + HostInfo.PORT);
// NIO使用轮询,当有请求连接时,则启动一个线程
int keySelect = 0;
while ((keySelect = selector.select()) > 0){ // selector.select() 会阻塞到这里,当有客户端连接时才会向下走
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey next = iterator.next();
if(next.isAcceptable()){ // 如果是连接的
SocketChannel accept = serverSocketChannel.accept();
if(accept != null){
// 启动一个线程放入线程池,进行读取当前客户端发送的消息,并且又把这个消息回传回去
executorService.submit(new ServerHandle(accept));
}
iterator.remove();
}
}
}
System.out.println("---");
executorService.shutdown();
serverSocketChannel.close();
}
}
NioClient
客户端进行输入信息,发向服务端:
package com.example.nio;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class NIOClient {
public static void main(String[] args) throws Exception{
SocketChannel clientChannel = SocketChannel.open();
clientChannel.connect(new InetSocketAddress(HostInfo.HOST_NAME,HostInfo.PORT));
ByteBuffer buffer = ByteBuffer.allocate(50);
boolean flag = true;
while (flag){
buffer.clear();
String input = InputUtil.getString("请输入待发送的信息:").trim();
buffer.put(input.getBytes()); //将数据存入缓冲区
buffer.flip(); // 重置缓冲区
clientChannel.write(buffer); //发送数据
buffer.clear();
int read = clientChannel.read(buffer);
buffer.flip();
System.err.print(new String(buffer.array(), 0, read));
if("byebye".equalsIgnoreCase(input)){
flag = false;
}
}
clientChannel.close();
}
}
Nioserver端的线程处理类
package com.example.nio;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class ServerHandle implements Runnable {
//客户端
private SocketChannel clientChannel;
// 循环结束标记
private boolean flag = true;
public ServerHandle(SocketChannel clientChannel){
this.clientChannel = clientChannel;
}
@Override
public void run() {
ByteBuffer byteBuffer = ByteBuffer.allocate(50);
try {
while (this.flag){
byteBuffer.clear();
int read = this.clientChannel.read(byteBuffer);
String msg = new String(byteBuffer.array(), 0, read).trim();
String outMsg = "【Echo】" + msg + "\n"; // 回应信息
if("byebve".equals(msg)){
outMsg = "会话结束,下次再见!";
this.flag = false;
}
byteBuffer.clear();
byteBuffer.put(outMsg.getBytes()); //回传信息放入缓冲区
byteBuffer.flip();
this.clientChannel.write(byteBuffer);// 回传信息
}
}catch (Exception e){
e.printStackTrace();
}
}
}
NioClient 客户端的 输入 工具类
package com.example.nio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputUtil {
private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in));
private InputUtil(){
}
public static String getString(String prompt){
boolean flag = true; //数据接受标记
String str = null;
while (flag){
System.out.println(prompt);
try {
str = KEYBOARD_INPUT.readLine(); // 读取一行数据
if(str == null || "".equals(str)){
System.out.println("数据输入错误,不允许为空!");
}else {
flag = false;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return str;
}
}
Nio通信配置类
package com.example.nio;
public class HostInfo {
public static final String HOST_NAME = "localhost";
public static final int PORT = 9999;
}