通过NIO实现非阻塞模式
服务器端
public class Server{
public static void main(String[] args){
//0.创建ByteBuffer对象
ByteBuffer buffer = ByteBuffer.allocate(16);
//1.创建服务器
ServerSocketChannel ssc = ServerSocketChannel.open();
//开启非阻塞模式,默认是阻塞模式
ssc.configureBlocking(false);
//2.绑定监听端口
ssc.bind(new InetSocketAddress(8080));
//3.创建SocketChannel集合
List<SocketChannel> channels = new ArrayList<>();
while(true){
//4.创建与客户端的连接
//非阻塞模式下,程序继续运行,如果没有连接建立,sc返回null
SocketChannel sc = ssc.accept();
if(sc != null){
//将客户端的连接设为非阻塞模式
sc.configureBlocking(false);
//5.将连接添加到SocketChannel集合中
channels.add(sc);
}
for(SocketChannel channel: channels){
//6.读取客户端发送的数据
//非阻塞模式下,程序继续运行,如果没有读到数据,返回值为0
int read = channel.read(buffer);
if(read > 0){ //读到了来自客户端的数据
buffer.flip(); //切换为读模式
debugRead(buffer);
buffer.clear(); //切换为写模式
}
}
}
}
}
客户端
public class Client{
public static void main(String[] args){
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress("localhost",8080));
System.in.read(); //阻塞方法 保持客户端与服务器的连接
}
}
非阻塞模式的缺点:即使没有连接建立,和可读数据,线程仍然在不断运行,一直占用 cpu资源