从SocketChannel对象池中获取的实例,使用时应注意的问题

从SocketChannel对象池中获取的实例,使用时应注意的问题
      从对象池中获取的实例,因为并不清楚该channel是否已经设置成正确的状态,所以在使用时最好重新设置一遍。有以下几点需要注意:
      1.在使用阻塞IO时,需要把该channel设置成阻塞的,即需要调用SocketChannel.configureBlocking(true);
      2.在使用非阻塞IO时,需要把该channel设置成非阻塞的,即需要调用SocketChannel.configureBlocking(false);
      3.如果该channel注册了selector,那么在返回该实例到对象池中,需要把注册的selector清除,即需要调用Selector的close方法。

      下面是一段应用场景的例子:


        
//  把命令输出
        channel.configureBlocking( true );
        PrintWriter writer 
=   new  PrintWriter(channel.socket().getOutputStream(),  false );
        writer.write(command.endsWith(
" \n " ?  command : command  +   " \n " );
        writer.flush();

        channel.configureBlocking(
false );

        
//  创建Selector
        Selector selector  =  Selector.open();
        
//  向Selector注册我们需要的READ事件
        SelectionKey skey  =  channel.register(selector, SelectionKey.OP_READ);

        boolean stop 
=   false ;
        
int  n  =   0 ;
        
int  read  =   0 ;
        ByteBuffer buffer 
=  ByteBuffer.allocate( 1024 );

        
//  轮询
         while  ( ! stop)  {
          
// 获取Selector返回的时间值
          n = selector.select();

          
// 当传回的值大于0事,读事件发生了
          if (n > 0{
         
// 处理发生的事件
         
          }

        }


        selector.close();

你可能感兴趣的:(从SocketChannel对象池中获取的实例,使用时应注意的问题)