java.nio.channels.SelectableChannel#close()源码实例Demo

下面列出了java.nio.channels.SelectableChannel#close() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ans-android-sdk   文件: BaseWebSocketServer.java
private void handleIOException(SelectionKey key, WebSocket conn, IOException ex) {
    // onWebsocketError( conn, ex );// conn may be null here
    if (conn != null) {
        conn.closeConnection(CloseFrame.ABNORMAL_CLOSE, ex.getMessage());
    } else if (key != null) {
        SelectableChannel channel = key.channel();
        if (channel != null && channel.isOpen()) { // this could be the case if the
            // IOException ex is a SSLException
            try {
                channel.close();
            } catch (IOException e) {
                // there is nothing that must be done here
            }
            if (WebSocketImpl.DEBUG) {
                System.out.println("Connection closed because of " + ex);
            }
        }
    }
}
 
源代码2 项目: netty-4.1.22   文件: AbstractNioChannel.java
/**
     * Create a new instance
     *
     * @param parent            the parent {@link Channel} by which this instance was created. May be {@code null}
     * @param ch                the underlying {@link SelectableChannel} on which it operates
     * @param readInterestOp    the ops to set to receive data from the {@link SelectableChannel}
     */
    protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
        super(parent);
        this.ch = ch;
        this.readInterestOp = readInterestOp;
        try {
//            设置非阻塞
            ch.configureBlocking(false);
        } catch (IOException e) {
            try {
                ch.close();
            } catch (IOException e2) {
                if (logger.isWarnEnabled()) {
                    logger.warn(
                            "Failed to close a partially initialized socket.", e2);
                }
            }

            throw new ChannelException("Failed to enter non-blocking mode.", e);
        }
    }
 
源代码3 项目: attic-apex-malhar   文件: NetworkManager.java
public synchronized void unregisterAction(ChannelAction action) throws IOException, InterruptedException
{
  ChannelConfiguration channelConfiguration = action.channelConfiguration;
  SelectableChannel channel = channelConfiguration.channel;
  if (channelConfiguration != null) {
    channelConfiguration.actions.remove(action);
    if (channelConfiguration.actions.size() == 0) {
      ConnectionInfo connectionInfo = channelConfiguration.connectionInfo;
      channelConfigurations.remove(channel);
      channels.remove(connectionInfo);
      channel.close();
    }
  }
  if (channels.size() == 0) {
    stopProcess();
  }
}
 
源代码4 项目: cava   文件: SelectorTest.java
@Test
void selectorRemovesKeysOnChannelCloseWhenSelecting() throws Exception {
  Pipe pipe = Pipe.open();

  Selector selector = Selector.open();
  SelectableChannel source = pipe.source();
  source.configureBlocking(false);

  SelectionKey key = source.register(selector, OP_READ);
  assertTrue(selector.keys().contains(key));

  source.close();
  assertTrue(selector.keys().contains(key));

  selector.selectNow();
  assertFalse(selector.keys().contains(key));
}
 
源代码5 项目: RipplePower   文件: WebSocketServer.java
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) {
	// onWebsocketError( conn, ex );// conn may be null here
	if( conn != null ) {
		conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() );
	} else if( key != null ) {
		SelectableChannel channel = key.channel();
		if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException
			try {
				channel.close();
			} catch ( IOException e ) {
				// there is nothing that must be done here
			}
			if( WebSocketImpl.DEBUG )
				System.out.println("Connection closed because of " + ex);
		}
	}
}
 
源代码6 项目: twister2   文件: Server.java
@Override
public void handleError(SelectableChannel ch) {
  SocketAddress channelAddress = ((SocketChannel) ch).socket().getRemoteSocketAddress();
  LOG.log(Level.FINE, "Connection is closed: " + channelAddress);

  BaseNetworkChannel channel = connectedChannels.get(ch);
  if (channel == null) {
    LOG.warning("Error occurred in non-existing channel");
    return;
  }
  channel.clear();
  progress.removeAllInterest(ch);
  try {
    ch.close();
  } catch (IOException e) {
    LOG.warning("Error closing conection in error handler");
  }
  connectedChannels.remove(ch);
  channelHandler.onClose((SocketChannel) ch);
}
 
源代码7 项目: twister2   文件: Client.java
@Override
public void handleError(SelectableChannel ch) {
  channel.clear();
  progress.removeAllInterest(ch);

  LOG.log(Level.SEVERE, "Error on channel " + ch);

  try {
    ch.close();
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "Failed to close connection in handleError", e);
  }

  isConnected = false;
  connecting = false;
  tryToConnect = false;
  channelHandler.onError(socketChannel, StatusCode.ERROR_CONN);
}
 
源代码8 项目: Slyther   文件: WebSocketServer.java
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) {
	// onWebsocketError( conn, ex );// conn may be null here
	if( conn != null ) {
		conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() );
	} else if( key != null ) {
		SelectableChannel channel = key.channel();
		if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException
			try {
				channel.close();
			} catch ( IOException e ) {
				// there is nothing that must be done here
			}
			if( WebSocketImpl.DEBUG )
				System.out.println( "Connection closed because of" + ex );
		}
	}
}
 
源代码9 项目: incubator-heron   文件: HeronServer.java
public void handleError(SelectableChannel channel) {
  SocketAddress channelAddress = ((SocketChannel) channel).socket().getRemoteSocketAddress();
  LOG.info("Handling error from channel: " + channelAddress);
  SocketChannelHelper helper = activeConnections.get(channel);
  if (helper == null) {
    LOG.severe("Inactive channel had error?");
    return;
  }
  helper.clear();
  LOG.info("Removing all interest on channel: " + channelAddress);
  nioLooper.removeAllInterest(channel);
  try {
    channel.close();
  } catch (IOException e) {
    LOG.severe("Error closing connection in handleError");
  }
  activeConnections.remove(channel);
  onClose((SocketChannel) channel);
}
 
源代码10 项目: incubator-heron   文件: HeronClient.java
public void handleError(SelectableChannel channel) {
  LOG.info("Handling Error. Cleaning states in HeronClient.");
  contextMap.clear();
  responseMessageMap.clear();
  messageMap.clear();
  socketChannelHelper.clear();
  nioLooper.removeAllInterest(channel);

  try {
    channel.close();
    LOG.info("Successfully closed the channel: " + channel);
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "Failed to close connection in handleError", e);
  }

  // Since we closed the channel, we set isConnected false
  isConnected = false;
  onError();
}
 
源代码11 项目: netty4.0.27Learn   文件: AbstractNioChannel.java
/**
 * Create a new instance
 *
 * @param parent            the parent {@link Channel} by which this instance was created. May be {@code null}
 * @param ch                the underlying {@link SelectableChannel} on which it operates
 * @param readInterestOp    the ops to set to receive data from the {@link SelectableChannel}
 */
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
    super(parent);
    this.ch = ch;
    this.readInterestOp = readInterestOp;
    try {
        ch.configureBlocking(false);
    } catch (IOException e) {
        try {
            ch.close();
        } catch (IOException e2) {
            if (logger.isWarnEnabled()) {
                logger.warn(
                        "Failed to close a partially initialized socket.", e2);
            }
        }

        throw new ChannelException("Failed to enter non-blocking mode.", e);
    }
}
 
源代码12 项目: craft-atom   文件: NioAcceptor.java
private void close(SelectableChannel sc) throws IOException {
	if (sc != null) {
		SelectionKey key = sc.keyFor(selector);
		if (key != null) {
			key.cancel();
		}
		sc.close();
	}
}
 
源代码13 项目: incubator-tuweni   文件: SelectorTest.java
@Test
void selectorRemovesKeysOnChannelCloseWhileSelecting() throws Exception {
  Pipe pipe = Pipe.open();

  Selector selector = Selector.open();
  SelectableChannel source = pipe.source();
  source.configureBlocking(false);

  SelectionKey key = source.register(selector, OP_READ);
  assertTrue(selector.keys().contains(key));

  CountDownLatch latch = new CountDownLatch(1);
  Future<?> job = executor.submit(() -> {
    latch.countDown();
    try {
      selector.select();
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  });

  latch.await();
  Thread.sleep(100);

  source.close();
  selector.wakeup();
  job.get();
  assertFalse(selector.keys().contains(key));
}
 
源代码14 项目: jdk1.8-source-analysis   文件: SelectorImpl.java
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
源代码15 项目: cava   文件: SelectorTest.java
@Test
void selectorRemovesKeysOnChannelCloseWhileSelecting() throws Exception {
  Pipe pipe = Pipe.open();

  Selector selector = Selector.open();
  SelectableChannel source = pipe.source();
  source.configureBlocking(false);

  SelectionKey key = source.register(selector, OP_READ);
  assertTrue(selector.keys().contains(key));

  CountDownLatch latch = new CountDownLatch(1);
  Future<?> job = executor.submit(() -> {
    latch.countDown();
    try {
      selector.select();
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  });

  latch.await();
  Thread.sleep(100);

  source.close();
  selector.wakeup();
  job.get();
  assertFalse(selector.keys().contains(key));
}
 
源代码16 项目: linstor-server   文件: TcpConnectorService.java
private void closeConnection(SelectionKey currentKey, boolean allowReconnect, boolean shuttingDown)
{
    Peer client = (TcpConnectorPeer) currentKey.attachment();
    if (client != null)
    {
        connObserver.connectionClosed(client, allowReconnect, shuttingDown);
        try
        {
            if (client.isConnected(false))
            {
                client.connectionClosing();
            }
        }
        catch (CancelledKeyException ignored)
        {
            // connectionClosing() calls interestOps on the selection Key, which may fail
        }
    }

    try
    {
        SelectableChannel channel = currentKey.channel();
        if (channel != null)
        {
            channel.close();
        }
    }
    catch (IOException closeIoExc)
    {
        // If close() fails with an I/O error, the reason may be interesting
        // enough to file an error report
        errorReporter.reportError(closeIoExc);
    }
    currentKey.cancel();
}
 
源代码17 项目: openjdk-jdk8u   文件: SelectorImpl.java
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
源代码18 项目: openjdk-jdk8u-backup   文件: SelectorImpl.java
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
源代码19 项目: openjdk-jdk9   文件: SelectorImpl.java
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
源代码20 项目: hottub   文件: SelectorImpl.java
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}