下面列出了java.nio.channels.SelectableChannel#close() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
}
}
/**
* 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);
}
}
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();
}
}
@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));
}
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);
}
}
}
@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);
}
@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);
}
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 );
}
}
}
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);
}
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();
}
/**
* 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);
}
}
private void close(SelectableChannel sc) throws IOException {
if (sc != null) {
SelectionKey key = sc.keyFor(selector);
if (key != null) {
key.cancel();
}
sc.close();
}
}
@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));
}
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();
}
}
@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));
}
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();
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}