设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 重新 试卷 创业者
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

BIO和NIO了解多少呢?一起从实践角度重新理解下吧(6)

发布时间:2019-10-23 18:24 所属栏目:21 来源:追逐仰望星空
导读:(2)解决方案二(缓存Socket,轮询数据是否准备好) publicclassServer{ publicstaticvoidmain(String[]args)throwsInterruptedException{ ByteBufferbyteBuffer=ByteBuffer.allocate(1024); ListSocketChannelsocketL

(2)解决方案二(缓存Socket,轮询数据是否准备好)

  1. public class Server { 
  2.     public static void main(String[] args) throws InterruptedException { 
  3.         ByteBuffer byteBuffer = ByteBuffer.allocate(1024); 
  4.          
  5.         List<SocketChannel> socketList = new ArrayList<SocketChannel>(); 
  6.         try { 
  7.             //Java为非阻塞设置的类 
  8.             ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 
  9.             serverSocketChannel.bind(new InetSocketAddress(8080)); 
  10.             //设置为非阻塞 
  11.             serverSocketChannel.configureBlocking(false); 
  12.             while(true) { 
  13.                 SocketChannel socketChannel = serverSocketChannel.accept(); 
  14.                 if(socketChannel==null) { 
  15.                     //表示没人连接 
  16.                     System.out.println("正在等待客户端请求连接..."); 
  17.                     Thread.sleep(5000); 
  18.                 }else { 
  19.                     System.out.println("当前接收到客户端请求连接..."); 
  20.                     socketList.add(socketChannel); 
  21.                 } 
  22.                 for(SocketChannel socket:socketList) { 
  23.                     socket.configureBlocking(false); 
  24.                     int effective = socket.read(byteBuffer); 
  25.                     if(effective!=0) { 
  26.                         byteBuffer.flip();//切换模式 写-->读 
  27.                         String content = Charset.forName("UTF-8").decode(byteBuffer).toString(); 
  28.                         System.out.println("接收到消息:"+content); 
  29.                         byteBuffer.clear(); 
  30.                     }else { 
  31.                         System.out.println("当前未收到客户端消息"); 
  32.                     } 
  33.                 } 
  34.             } 
  35.         } catch (IOException e) { 
  36.             // TODO Auto-generated catch block 
  37.             e.printStackTrace(); 
  38.         } 
  39.     } 

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读