Code example for SocketChannel

Methods: close, read

0
    processInBuffer(); 
  } 
   
  public void close() { 
    try { 
      sc.close();
    } catch (IOException e) {
      // Ignore 
    } 
  } 
   
  /** 
   * Reads from the socket into the internal buffer. This method should  
   * be called only from the SelectorThread class. 
   */ 
  public void handleRead() { 
    try {       
      // Reads from the socket       
      // Returns -1 if it has reached end-of-stream 
      int readBytes = sc.read(inBuffer);      
      // End of stream??? 
      if (readBytes == -1) {
        // End of stream. Closing channel... 
        close(); 
        listener.socketDisconnected(this);
        return; 
      } 
       
      // Nothing else to be read? 
      if (readBytes == 0) {        
        // There was nothing to read. Shouldn't happen often, but  
        // it is not an error, we can deal with it. Ignore this event 
        // and reactivate reading. 
        reactivateReading(); 
        return; 
      } 
       
      // There is some data in the buffer. Processes it. 
      inBuffer.flip();
      processInBuffer(); 
    } catch (IOException ex) {
      // Serious error. Close socket. 
      listener.socketException(this, ex);
      close(); 
    } 
  } 
   
  /** 
   * Processes the internal buffer, converting it into packets if enough 
   * data is available. 
   */ 
  private void processInBuffer() throws IOException {     
    ByteBuffer packet = protocolDecoder.decode(inBuffer);
    // A packet may or may not have been fully assembled, depending 
    // on the data available in the buffer 
    if (packet == null) {      
      // Partial packet received. Must wait for more data. All the contents 
      // of inBuffer were processed by the protocol decoder. We can 
      // delete it and prepare for more data. 
      inBuffer.clear();
      reactivateReading(); 
    } else {       
      // A packet was reassembled. 
      listener.packetArrived(this, packet);
      // The inBuffer might still have some data left. Perhaps 
      // the beginning of another packet. So don't clear it. Next 
      // time reading is activated, we start by processing the inBuffer 
      // again. 
    } 
  } 
 
  /** 
   * Disable interest in reading. 
   * @throws IOException  
   */ 
  public void disableReading() throws IOException { 
    selector.removeChannelInterestNow(sc, SelectionKey.OP_READ);    
  } 
   
  /** 
   * Enables interest in reading. 
   * @throws IOException 
   */ 
  private void reactivateReading() throws IOException { 
    selector.addChannelInterestNow(sc, SelectionKey.OP_READ);
  } 
   
  /** 
   * Sends a packet using non-blocking writes. One packet cannot be sent  
   * before the previous one has been dispatched. The caller must ensure