1.Server
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NioServer {
public static void main(String[] args) throws IOException {
//创建服务器
ServerSocketChannel server = ServerSocketChannel.open();//打开一个服务器
//绑定地址
server.bind(new InetSocketAddress(6666));//非阻塞的方法
//配置成非阻塞式的channel
server.configureBlocking(false);
//此外需要一个IO多路复用器
Selector selector = Selector.open();
//注册channel到selector上去
server.register(selector, SelectionKey.OP_ACCEPT);//关注连接操作选项
while (true){
//选择器进行系统调用,返回值代表发生事件的个数
//0表示超时,-1表示错误
int select = selector.select();//这个方法可以设置超时时间
//如果不设置超时时间,那么这个方***一直在这里阻塞
//System.out.println(select);
//由于select()方法是阻塞的,程序执行到此处时就代表有事件发生;
Set<SelectionKey> selectionKeys = selector.selectedKeys();
//前面拿到了所有产生了事件的集合,于是就可以使用迭代器遍历
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
//主要的点,关注的事情一旦处理完成了,就是用迭代器的方式删除这个事件
//能够关注不同的事件
if (selectionKey.isAcceptable()){
System.out.println("有人连接我了");
iterator.remove();
}
if (selectionKey.isReadable()){
System.out.println("有新的可读");
}
}
}
}
}
2、
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class NioClient {
public static void main(String[] args) throws IOException, InterruptedException {
SocketChannel client = SocketChannel.open();
client.configureBlocking(false);
client.connect(new InetSocketAddress(6666));
Thread.sleep(100000);
}
}