服务端
/**
* @Author: zhengyun
* @Date: 2021/3/23 23:30
*/
public class NIOServer {
public static void main(String[] args) throws Exception {
//创建ServerSocketChannel -> ServerSocket
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//得到一个Selecor对象
Selector selector = Selector.open();
//绑定一个端口6666,在服务器端监听
serverSocketChannel.socket().bind(new InetSocketAddress(6666));
//设置为非阻塞
serverSocketChannel.configureBlocking(false);
//把serverSocketChannel 注册到 selector 中,事件为OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//循环等待客户端连接
while (true){
if(selector.select(3000)==0){//没有事件发生
System.out.println("服务器等待了3秒,无连接");
continue;
}
//如果返回>0,就获取相关的selectionKey集合
//1.如果返的>0,表示已经获取到关注的事件
//2.selector.selectedKeys()返回关注事件的集合
//通过selectionKeys 反向获取通道
Set<SelectionKey> selectionKeys = selector.selectedKeys();
//遍历Set<SelectionKey>, 使用迭代器遍历
Iterator<SelectionKey> keyIterator = selectionKeys.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);
//将socketChannel 注册到selec,关注事件为OP_READ,同时给socketChannel关联一个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()));
}
//手动从集合中移动当前的selectionKey,防止重复操作
keyIterator.remove();
}
}
}
}
客户端
/**
* @Author: zhengyun
* @Date: 2021/3/24 0:08
*/
public class NIOChlient {
public static void main(String[] args) throws Exception{
//得到一个网络通道
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();
}
}
结果