NIO实现服务端

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;
/**
* @author TAO
* @description: NIOServer
* @date 2021/6/27 23:37
*/
public class NIOServer {

public static void main(String[] args) throws Exception {

//1.创建ServerSocketChannel --> ServerSocket
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

///2.得到一个Selector对象
Selector selector = Selector.open();

//3.绑定一个端口6666在服务器端监听
serverSocketChannel.socket().bind(new InetSocketAddress(6666));

//4.设置为非阻塞
serverSocketChannel.configureBlocking(false);

//5.把ServerSocketChannel注册到selector 监听事件为 OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

//6.循环等待客户端连接(干活)
while (true) {

//6.1 这里我们等待1秒,如果没有事件发生,返回(监控客户端)
if (selector.select(1000)==0){//nio非阻塞式的优势
System.out.println("服务端等待1秒,无连接");
continue;
}

//如果返回的>0,
// 1.返回的>0标识获取到关注的事件
// 2.selector.selectedKeys() 返回关注的时间集合
// 通过selectionKeySets 方向获取通道
//6.2 得到SelectionKey,判断通道里的事件
Iterator<SelectionKey> keyIterator=selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {

//获取到SelectionKey
SelectionKey key = keyIterator.next();

//根据key 对应的通道发生的事件做对应的处理
if (key.isAcceptable()) {//如果是 OP_ACCEPT ,有新的客户端连接 客户端连接请求事件
//该客户端生成一个SocketChannel
SocketChannel socketChannel = serverSocketChannel.accept();

//System.out.println("客户端连接成功!!!生成了一个socketChannel--->"+socketChannel.hashCode());

//将socketChannel设置为非阻塞的
socketChannel.configureBlocking(false);//防止此异常 Exception in thread "main" java.nio.channels.IllegalBlockingModeException

//将socketChannel 注册到selector 关注事件为OP_READ
//关联一个Buffer
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}

if (key.isReadable()){//发生OP_READ 读取客户端数据事件
//通过key方向获取对应的channel
SocketChannel channel = (SocketChannel) key.channel();

//获取到该channel关联的buffer
ByteBuffer buffer = (ByteBuffer) key.attachment();

channel.read(buffer);
System.out.println("form 客户端"+new String(buffer.array()));
}
//6.3 手动从集合中移除当前的selectionKey,防止重复操作
keyIterator.remove();
}
}
}
}

NIO实现客户端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
* @description: NIOClient
* @author TAO
* @date 2021/6/27 23:57
*/
public class NIOClient {

public static void main(String[] args) throws IOException {
//得到一个网络通道
SocketChannel socketChannel = SocketChannel.open();

//设置为非阻塞
socketChannel.configureBlocking(false);

//根据服务端的ip和端口
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

//连接服务器
if (!socketChannel.connect(inetSocketAddress)){

while (!socketChannel.finishConnect()){
System.out.println("因为连接需要时间,客户端不会阻塞,可以做其他操作...");
}
}

//如果连接成功,就发送数据
String str = "hello";
ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
//发送数据,将buffer数据写入channel
socketChannel.write(buffer);
System.in.read();
}
}