通过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资源

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值